$_POST

$HTTP_POST_VARS [obsoleta]

(PHP 4 >= 4.1.0, PHP 5)

$_POST -- $HTTP_POST_VARS [obsoleta]Variables HTTP POST

Descripción

Un array asociativo de variables pasadas al script actual a través del método HTTP POST.

$HTTP_POST_VARS contiene la misma información inicial, pero no es una superglobal. (Nótese que $HTTP_POST_VARS y $_POST son diferentes variables y que PHP las trata de forma distinta)

Historial de cambios

Versión Descripción
4.1.0 Se introdujo $_POST y $HTTP_POST_VARS quedó obsoleta.

Ejemplos

Ejemplo #1 Ejemplo de $_POST

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

Asumiendo que el usuario envió por el método POST nombre=Juan

El resultado del ejemplo sería algo similar a:

Hola Juan!

Notas

Nota:

Esta es una 'superglobal' o una variable automatic global. Significa simplemente que es una variable que está disponible en cualquier parte del script. No hace falta hacer global $variable; para acceder a la misma desde funciones o métodos.

add a note add a note

User Contributed Notes 10 notes

up
26
james dot ellis at gmail dot com
5 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
4
paul at youngish dot homelinux^org
5 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
Mohammad Tawaha
23 days ago
but to make this $_Post work
You Must write in the .HTML file in the form ( action="http://example.php")
<form action="http://example.php" method="post">
....
</form>
if you Do Not put http:// before the .php file it will Not work with you>>>
Thanks!
up
0
CXJ
1 month ago
Note that $_POST is NOT set for all HTTP POST operations,  but only for specific types of POST operations.  I have not been able to find documentation, but here's what I've found so far.

$_POST _is_ set for:

Content-Type: application/x-www-form-urlencoded

In other words,  for standard web forms.

$_POST is NOT set for:

Content-Type:text/xml

A type used for a generic HTTP POST operation.
up
0
yesk13 at gmail dot com
4 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
-1
perdondiego at mailinator dot com
2 years 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
-8
php dot net at bigbadaboom dot net
5 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
-7
paul dot chubb at abs dot gov dot au
5 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
-11
telconstar99 at hotnospampleasemail dot com
5 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
-23
initself
5 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;
?>
To Top