PHP $_POST
The $_POST superglobal contains an array of variables received via the HTTP POST method.
PHP superglobals are built-in variables that are always accessible in all scopes!
$_POST in HTML Forms
An HTML form submits data via the HTTP POST method if the form's method attribute is set to "post".
To demonstrate this, we start by creating a simple HTML form:
HTML file:
<html>
<body>
<form method="post" action="demo_request.php">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>
When a user clicks the submit button, the form data is sent to the PHP file specified in the action attribute of the <form> tag.
In the PHP file we can use the $_POST variable to collect the value of the input field.
PHP file:
$name = htmlspecialchars($_POST['fname']);
echo $name;
Note: Always validate and sanitize all data collected from superglobals like
$_POSTbefore using it, to prevent security vulnerabilities like XSS attacks. Thehtmlspecialchars()function used above is one way to do it. More robust filtering can be done by using the PHP filter functions.
Put it Together
In the example below we have put the HTML form and PHP code in the same PHP file:
Example
<html>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>