PHP $_POST


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 http://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.

CharacterReplacement
& (ampersand)&amp;
" (double quote)&quot;
' (single quote)&#039; or &apos;
< (less than)&lt;
> (greater than)&gt;

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

Updated on: 21-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements