In this tutorial, you’ll learn about the PHP $_POST
superglobal, which is used to collect data sent to the server via the HTTP POST method. This is particularly useful for handling form submissions securely.
PHP Superglobal $_POST
1. What is the $_POST Superglobal?
The $_POST
superglobal is an associative array that allows you to access data sent from an HTML form using the POST method. It is a more secure method than GET, as the data is not visible in the URL.
2. How $_POST Works
When a form is submitted using the POST method, the data is sent to the server in the request body, and the $_POST
superglobal is populated with that data. You can access the data using the name attribute of the input fields in the form.
3. Accessing POST Data
To access data from the $_POST
superglobal, use the keys that correspond to the input names in your HTML form. Here’s an example:
<?php
// Assuming a form submission with input field name "email"
$email = $_POST['email'];
echo "Email: " . htmlspecialchars($email);
?>
This retrieves the value of the input field named email
.
4. Example: Using $_POST with a Form
Here’s a complete example demonstrating how to use $_POST
with a simple form:
<form action="" method="POST">
<label for="email">Email:</label>
<input type="email" name="email" id="email" required>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'];
echo "Thank you for submitting your email: " . htmlspecialchars($email) . "!";
}
?>
This form collects an email address and displays a thank you message upon submission.
5. Handling Multiple Inputs
You can handle multiple inputs using the $_POST
superglobal in a similar way:
<form action="" method="POST">
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name" required>
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name" required>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
echo "Welcome, " . htmlspecialchars($firstName) . " " . htmlspecialchars($lastName) . "!";
}
?>
This example collects both first and last names and displays a welcome message upon submission.
6. Conclusion
The $_POST
superglobal is essential for handling form data in PHP securely. By using POST, you can protect sensitive information and ensure a better user experience. Always remember to validate and sanitize the input to prevent security vulnerabilities.