In PHP, the $_POST superglobal is used to collect form data submitted via the HTTP POST method. Unlike $_GET, data sent using $_POST is not visible in the URL, making it more secure for handling sensitive information like passwords.
🔹 How Does $_POST Work?
When a user submits a form using method="post", PHP can access the values using $_POST.
📝 Example 1: Simple Form Using $_POST
This example collects a username and password from an HTML form.
<form action="welcome.php" method="post">
Username: <input type="text" name="username"> <br>
Password: <input type="password" name="password"> <br>
<input type="submit" value="Login">
</form>
When the form is submitted, data is sent to welcome.php:
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
echo "Welcome, $username!";
} else {
echo "Please enter your details.";
}
?>
🔹 Handling Missing or Empty $_POST Values
Always check if the form fields are set to avoid errors.
<?php $username = isset($_POST['username']) ? $_POST['username'] : "Guest"; echo "Hello, $username!"; ?>
Output: If no username is provided, it defaults to “Guest”.
🔹 $_POST vs. $_GET – Key Differences
$_POST– Data is not visible in the URL (secure for passwords, personal details).$_GET– Data is visible in the URL (useful for search queries, navigation).
🔹 Securing User Input in $_POST
To prevent XSS (Cross-Site Scripting), always sanitize user input:
<?php $username = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : "Guest"; echo "Welcome, $username!"; ?>
Using htmlspecialchars() converts special characters to HTML entities, preventing script injections.
🎯 Key Takeaways
$_POSTcollects form data sent via HTTP POST.- More secure than
$_GETbecause data is not exposed in the URL. - Always use input validation to protect against security threats.
📝 Practice Time!
Modify the form to collect favorite color and email, then display them using $_POST!