PHP – $_POST
$_POST is one of the predefined or superglobal variables in PHP. It is an associative array of key-value pairs passed to a URL by the HTTP POST method that uses URLEncoded or multipart/form-data content-type in the request.
-
$HTTP_POST_VARS also contains the same information as $_POST, but is not a superglobal, and now been deprecated.
-
The easiest way to send data to a server with POST request is specifying the method attribute of HTML form as POST.
Assuming that the URL in the browser is “http://localhost/hello.php”, method=POST is set in a HTML form “hello.html” as below −
<html> <body> <form action="hello.php" method="post"> <p>First Name: <input type="text" name="first_name"/> </p> <p>Last Name: <input type="text" name="last_name" /> </p> <input type="submit" value="Submit" /> </form> </body> </html>
The “hello.php” script (in the document root folder) for this exercise is as follows:
<?php echo "<h3>First name: " . $_POST[''first_name''] . "<br /> " . "Last Name: " . $_POST[''last_name''] . "</h3>"; ?>
Now, open http://localhost/hello.html in your browser. You should get the following output on the screen −
As you press the Submit button, the data will be submitted to “hello.php” with the POST method.
You can also mix the HTML form with PHP code in hello.php, and post the form data to itself using the “PHP_SELF” variable −
<html> <body> <form action="<?php echo $_SERVER[''PHP_SELF''];?>" method="post"> <p>First Name: <input type="text" name="first_name"/> </p> <br /> <p>Last Name: <input type="text" name="last_name" /></p> <input type="submit" value="Submit" /> </form> <?php echo "<h3>First Name: " . $_POST[''first_name''] . "<br /> " . "Last Name: " . $_POST[''last_name''] . "</h3>"; ?> </body> </html>
It will produce the following output −