PHP $_POST
$_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post".
$_POST is also widely used to pass variables.
PHP $_POST in Form Handling
The page in the example below holds a form with one text input and a submit button. Clicking "Submit" sends what the user typed to whichever file the form's action attribute names. Here that is the page itself, so one script both displays the form and processes it. After the submit, the typed value is waiting in $_POST:
Collect Form Data with $_POST
Read what the user typed into an input field with $_POST:
Output: PHP script
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="name">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
if (empty($name)) {
echo "Name is empty";
} else {
echo "Hello " . $name;
}
}
?>
</body>
</html>
Example Explained
The HTML form above sends data using the POST method to the current page. This means that the form data is available in the $_POST superglobal array.
Here is how it works:
- The
actionattribute is set to$_SERVER['PHP_SELF'], so the form data goes back to the current page - The
method="post"attribute tells the browser to send the form data via HTTP POST - The
$_POST['name']entry holds whatever was typed into the input withname="name"
Note: Use isset() to check if the $_POST variable is set before trying to access its value. This avoids errors when the page is loaded for the first time (before the form is submitted). The example gets the same protection by checking $_SERVER["REQUEST_METHOD"] first.
$_POST in Links
$_POST can not be used to send data via links. For sending data via links, use $_GET instead.
Since POST data is not visible in the URL, it is more suitable for sending sensitive data like passwords.