downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

$_FILES> <$_GET
[edit] Last updated: Fri, 26 Apr 2013

view this page in

$_POST

$HTTP_POST_VARS [deprecated]

$_POST -- $HTTP_POST_VARS [deprecated]HTTP POST variables

Descrição

Um array associativo de variáveis passados para o script atual via método HTTP POST.

$HTTP_POST_VARS contém a mesma informação inicial, mas não é uma superglobal. (Note que $HTTP_POST_VARS e $_POST são variáveis diferentes e que o PHP manuseia-as diferentemente)

Changelog

Versão Descrição
4.1.0 Introduzida a $_POST que torna obsoleta a $HTTP_POST_VARS.

Exemplos

Exemplo #1 Exemplo da $_POST

<?php
echo 'Hello ' htmlspecialchars($_POST["name"]) . '!';
?>

Assumindo que o usuário tenha postado name=Hannes

O exemplo acima irá imprimir algo similar à:

Hello Hannes!

Notas

Nota:

Esta é uma 'superglobal', ou global automática, variável. Isto simplismente significa que ela está disponível em todos escopos pelo script. Não há necessidade de fazer global $variable; para acessá-la dentro de uma função ou método.



$_FILES> <$_GET
[edit] Last updated: Fri, 26 Apr 2013
 
add a note add a note User Contributed Notes $_POST - [12 notes]
up
3
perdondiego at mailinator dot com
1 year ago
In response to "php dot net at bigbadaboom dot net", adding the value attr to the image submit button may not work in older browser (Opera 9.x for example).

A better solution would be to add a hidden input (<input name="hidden" .... /> in the form to handle both cases: when we have a submit button or an image button for submitting
up
3
telconstar99 at hotnospampleasemail dot com
4 years ago
<?
//If we submitted the form
if(isset($_POST['submitMe']))
{
     echo("Hello, " . $_POST['name'] . ", we submitted your form!");
}
//If we haven't submitted the form
else
{
?>
    <form action="<?=$_SERVER['PHP_SELF']?>" method="POST">
    <input type="text" name="name"><br>
    <input type="submit" value="submit" name="submitMe">
    </form>
<?
}
?>
up
7
yesk13 at gmail dot com
3 years ago
you may have multidimensional array in form inputs

HTML Example:

<input name="data[User][firstname]" type="text" />
<input name="data[User][lastname]" type="text" />
...

Inside php script
after submit you can access the individual element like so:

$firstname = $_POST['data']['User']['firstname'];
...
up
2
james dot ellis at gmail dot com
4 years ago
One feature of PHP's processing of POST and GET variables is that it automatically decodes indexed form variable names.

I've seem innumerable projects that jump through extra & un-needed processing hoops to decode variables when PHP does it all for you:

Example pseudo code:

Many web sites do this:

<form ....>
<input name="person_0_first_name" value="john" />
<input name="person_0_last_name" value="smith" />
...

<input name="person_1_first_name" value="jane" />
<input name="person_1_last_name" value="jones" />
</form>

When they could do this:

<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>

With the first example you'd have to do string parsing / regexes to get the correct values out so they can be married with other data in your app... whereas with the second example.. you will end up with something like:
<?php
var_dump
($_POST['person']);
//will get you something like:
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>

This is invaluable when you want to link various posted form data to other hashes on the server side, when you need to store posted data in separate "compartment" arrays or when you want to link your POSTed data into different record handlers in various Frameworks.

Remember also that using [] as in index will cause a sequential numeric array to be created once the data is posted, so sometimes it's better to define your indexes explicitly.
up
1
initself
4 years ago
# This will convert $_POST into a query string

<?php
$query_string
= "";
if (
$_POST) {
 
$kv = array();
  foreach (
$_POST as $key => $value) {
   
$kv[] = "$key=$value";
  }
 
$query_string = join("&", $kv);
}
else {
 
$query_string = $_SERVER['QUERY_STRING'];
}
echo
$query_string;
?>
up
1
php dot net at bigbadaboom dot net
4 years ago
Make sure your submit buttons (ie. <input type="submit"> etc) have a 'value' attribute.  If they don't, the value won't appear in $_POST and so isset($_POST["submit"]) won't work either.

Example:

<input type="submit" name="submit">

isset($_POST["submit"]) returns false

<input type="submit" name="submit" value="Next">

isset($_POST["submit"]) returns true.

This might seem obvious for text buttons since they need a label anyway.  However, if you are using image buttons, it might not occur to you that you need to set a value attribute as well.  For example, the value attribute is required in the following element if you want to be able to detect it in your script.

<input type="image" name="submit" src="next.gif" value="Next">
up
0
toader_alexandru at yahoo dot com
3 years ago
When you have a form with some radio:
<?php
<form method='post'>
<
input type='radio' name='55' value='1' >
<
input type='radio' name='55' value='2' >
<
input type='radio' name='55' value='3' >
<
input type='radio' name='55' value='4' >

<
input type='submit' value='ok' >
</
form>

?>

if the name of the radio is a number will be returned by $_POST as INT!!!! not string as the manual says

if the name of the radio is 'test' will be of course returned ad string.

So your post array will look like this:
<?php
array
167302 => string '167308' (length=6)
167314 => string '167344' (length=6)
167347 => string '5867521' (length=7)
'3754952706' => string '3754952706' (length=10)
'3744466946' => string '3744466946' (length=10)
'3740271617' => string '3740271617' (length=10)
'3749709826' => string '3749709826' (length=10)
'3749708801' => string '1' (length=1)
'meta' =>
array
'hasJavascript' => string '0' (length=1)
'timeToComplete' => string '1264769572.6144' (length=15)
'Submit' => string 'Next' (length=4)

?>

Note the first 3 keys are int not string

This could affect you if you do some operations for example if you do an array_merge with your post values:

<?php
$arr1
= array(
167302 => '167308',
167314 => '167344',
167347 => '5867521',
'3754952706' => '3754952706',
'3744466946' => '3744466946',
'3740271617' => '3740271617',
'3749709826' => '3749709826',
'3749708801' => '1'
);

$arr2 = array(
'meta' =>
array (
'hasJavascript' => '0',
'timeToComplete' => '1264769572.6144'
)
);

?>

if you do :
<?php
$values
= array_merge($arr1, $arr2);//this is done by zend in $form->getValues()
?>

guess what will be the result? your numeric keys will be reindexed starting from 0.

and your post values will look like this:

<?php

0
=> string '167308' (length=6)
1 => string '167344' (length=6)
2 => string '5867521' (length=7)
'3754952706' => string '3754952706' (length=10)
'3744466946' => string '3744466946' (length=10)
'3740271617' => string '3740271617' (length=10)
'3749709826' => string '3749709826' (length=10)
'3749708801' => string '1' (length=1)
'meta' =>
array
'hasJavascript' => string '0' (length=1)
'timeToComplete' => string '1264769572.6144' (length=15)

?>
up
0
paul at youngish dot homelinux^org
4 years ago
For a page with multiple forms here is one way of processing the different POST values that you may receive.  This code is good for when you have distinct forms on a page.  Adding another form only requires an extra entry in the array and switch statements.

<?php

 
if (!empty($_POST))
 {
   
// Array of post values for each different form on your page.
   
$postNameArr = array('F1_Submit', 'F2_Submit', 'F3_Submit');       

   
// Find all of the post identifiers within $_POST
   
$postIdentifierArr = array();
       
    foreach (
$postNameArr as $postName)
    {
        if (
array_key_exists($postName, $_POST))
        {
            
$postIdentifierArr[] = $postName;
        }
    }

   
// Only one form should be submitted at a time so we should have one
    // post identifier.  The die statements here are pretty harsh you may consider
    // a warning rather than this.
   
if (count($postIdentifierArr) != 1)
    {
       
count($postIdentifierArr) < 1 or
            die(
"\$_POST contained more than one post identifier: " .
              
implode(" ", $postIdentifierArr));

       
// We have not died yet so we must have less than one.
       
die("\$_POST did not contain a known post identifier.");
    }
        
    switch (
$postIdentifierArr[0])
    {
    case
'F1_Submit':
       echo
"Perform actual code for F1_Submit.";
       break;

    case
'Modify':
       echo
"Perform actual code for F2_Submit.";
       break;
          
    case
'Delete':
       echo
"Perform actual code for F3_Submit.";
       break;
    }
}
else
// $_POST is empty.
{
    echo
"Perform code for page without POST data. ";
}
?>
up
0
Anonymous
2 months ago
This is a handy function that can be used for validating user input

<?php
/*
     * @var $func is used like a callback function
     *      it will return whatever value you make it return
     *
     * post( "$param" )
     * post( "$param" , 55 ),
     * post( "$param" , 55 , "/[^a-z]/i" )
     * post( "$param" , 55 , "/[^a-z]/i" , FILTER_SANATIZE_SPECIAL_CHARS)
     * post( "$param" ,55 , "/[^a-z0-9.]/i" , FILTER_SANATIZE_SPECIAL_CHARS, function($str){ if($str === 'red' ){ return false; }else { return true; } })
     * post( "$param" , '/[^a-z]/i')
     * post( "$param",function(){} )
     *
     * even more combinations workd. but to be SAFE skipping any value with NULL will alway work
     *
     * post("$param" , NULL , NULL , NULL , function(){});
     * post("$param" , NULL , NULL , '/[^a-z]/i');
     * post("$param" , 55 , NULL , '/[^a-z]/i');
     *
     * even more will work.
     *
     * get a post value from global $_POST
     */
   
function post($param , $max_len = 256 , $filter = FILTER_SANITIZE_FULL_SPECIAL_CHARS, $replace = NULL , $func = NULL)
    {
        if(
$filter === NULL)    #   if filter is skipped using NULL
       
{
           
$filter = FILTER_SANITIZE_FULL_SPECIAL_CHARS;   //set it to its default
       
}elseif(is_string($filter)) //else if its a string
       
{
           
$replace = $filter; //set the replace to the string
           
           
$filter = FILTER_SANITIZE_FULL_SPECIAL_CHARS;   //and this back to its default
       
}elseif (!is_integer($filter)) {
           
           
$func = $filter;
           
           
$filter = FILTER_SANITIZE_FULL_SPECIAL_CHARS;
        }
       
        if(
$max_len === NULL)//if max length was skipped
       
{
           
$max_len = 256; //set to default
       
}
       
        if(!
is_int($max_len))
        {
            if(
is_string($max_len))
            {
               
$replace = $max_len;
            }elseif(
is_callable($max_len))
            {
               
$func = $max_len;
            }
           
           
$max_len = 256;
        }
       
       
$sub_input = '';
       
        if ( isset(
$_POST[$param]) && !empty($_POST[$param])) # if the post paramter is set
       
{  
           
$user_input = filter_input(INPUT_POST, $param, $filter);
           
            if (
$max_len > strlen($user_input) ) # if max length is greater then the len of the string
           
{
               
$max_len = strlen($user_input);      # we use the max length of the string
           
}
           
           
$sub_input = substr($user_input, 0 , $max_len);
        }else
        {
            return
$sub_input;
        }
       
       
$return = preg_quote($sub_input);  #   take care of escape characters
       
       
if($replace !== NULL)
        {  
           
$return = preg_replace($replace, '' , $return);
        }
       
        if (
$func !== NULL)
        {
            return
$func($return);
        }
       
        return
$return;
    }
?>
up
0
eddyvlad at eddyvlad dot com
4 years ago
Take note that all $_POST values are (string).
If your form field should accept both numeric and alphabets but exclude a value of 0, you will have a problem.

<?php
## Using Equal operator
if($_POST['myfield'] == 0){
    echo
'You cannot set it to 0';
} else {
    echo
'Correct';
}
# You will get the following results

// $_POST['myfield'] = 0;
// Output: You cannot set it to 0;

// $_POST['myfield'] = 1;
// Output: Correct;

// $_POST['myfield'] = 'test';
// Output: You cannot set it to 0;

## Using Identical operator
if($_POST['myfield'] === 0){
    echo
'You cannot set it to 0';
} else {
    echo
'Correct';
}
# You will get the following results

// $_POST['myfield'] = 0;
// Output: Correct;

// $_POST['myfield'] = 1;
// Output: Correct;

// $_POST['myfield'] = 'test';
// Output: Correct;

// You need to convert numeric values to integer and use identical operator
$_POST['myfield'] = is_numeric($_POST['myfield']) ? (int)$_POST['myfield'] : $_POST['alias'];
if(
$_POST['myfield'] === 0){
    echo
'You cannot set it to 0';
} else {
    echo
'Correct';
}
# Now you will get the following results

// $_POST['myfield'] = 0;
// Output: You cannot set it to 0;

// $_POST['myfield'] = 1;
// Output: Correct;

// $_POST['myfield'] = 'test';
// Output: Correct;
?>
up
0
paul dot chubb at abs dot gov dot au
4 years ago
Nasty bug in IE6, Apache2 and mod_auth_sspi. Essentially if the user presses the submit button too quickly, $_POST (and the equivalents) comes back empty. The workaround is to set Apache's KeepAliveTimeout to 1. This would mean that the user would need to push submit within a second to trigger the issue.
up
-6
jairhumberto at gmail dot com
4 years ago
<?php

foreach($_POST as $k=>$v) $$k=$v;
//to use $_POST["example"] as $example

foreach($_GET as $k=>$v) $$k=$v;
//to use $_GET["example"] as $example

//or better:

foreach(${"_" . $_SERVER["REQUEST_METHOD"]} as $k=>$v) $$k=$v;
//to use $_GET["example"] or $_POST["example"] as $example

?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites