Introduction
$_POST is a predefined variable which is an associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request.
$HTTP_POST_VARS also contains the same information, but is not a superglobal, and now been deprecated.
Easiest way to send data to server with POST request is specifying method attribute of HTML form as POST. Assuming that the URL in browser is https://localhost/testscript.php, method=POST is set in a HTML form test.html as below −
<form action="testscript.php" method="POST"> <input type="text" name="name"> <input type="text" name="age"> <input type ="submit" value="submit"> </form>
The PHP script is as follows:
Example
<?php echo "Name : " . $_POST["name"] . "<br>"; echo "Age : " . $_POST["age"]; ?>
Output
This will produce following result −
Name : xyz Age : 20
In following example, htmlspecialchars() function is used to convert characters in HTML entities.
Character | Replacement |
---|---|
& (ampersand) | & |
" (double quote) | " |
' (single quote) | ' or ' |
< (less than) | < |
> (greater than) | > |
Assuming that the user posted dta as name=xyz and age=20
Example
<?php echo "Name: " . htmlspecialchars($_POST["name"]) . "<br>"; echo "age: " . htmlspecialchars($_POST["age"]) . "<br>"; ?>
Output
This will produce following result −
Name : xyz Age : 20