Google News
logo
PHP Program to $_POST - Used to collect form data after submitting an HTML form. Also used to pass variables
In the following example of PHP program that demonstrates the usage of `$_POST` superglobal variable to collect form data submitted through an HTML form :
Program :
<!DOCTYPE html>
<html>
<head>
	<title>PHP $_POST Example</title>
</head>
<body>

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];

	echo "<h2>Form Data:</h2>";
	echo "Name: $name <br>";
	echo "Email: $email <br>";
	echo "Message: $message <br>";
}
?>

<h2>Contact Form</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
	<label for="name">Name:</label>
	<input type="text" id="name" name="name"><br>

	<label for="email">Email:</label>
	<input type="email" id="email" name="email"><br>

	<label for="message">Message:</label>
	<textarea id="message" name="message"></textarea><br>

	<input type="submit" value="Submit">
</form>

</body>
</html>
In this program, we first check if the request method is `POST` using `$_SERVER['REQUEST_METHOD']` superglobal variable. If it is `POST`, we collect the form data using `$_POST` superglobal variable and display it.

The HTML form contains `name`, `email`, and `message` fields that will be submitted to the same PHP script. The `action` attribute of the form is set to `<?php echo $_SERVER['PHP_SELF'];?>` to submit the form to the same script.

When the user submits the form, the form data is collected using `$_POST` superglobal variable and displayed.

`$_POST` is also used to pass variables from one PHP script to another using HTTP POST method. In this case, the form data is submitted to a different PHP script using the `action` attribute of the form. The receiving PHP script can access the variables using `$_POST` superglobal variable.