The PHP $_POST superglobal is a pivotal cog when processing submitted form data. With over 82% of websites leveraging PHP, understanding POST variables is an essential skill for back-end developers. This comprehensive 3500 word guide aims to make you a POST variable ninja by covering critical concepts, security, practical applications and expert best practices.
What Are PHP POST Variables?
In dynamic web applications, the POST request method facilitates secure server-side form handling. The $_POST variable pre-packages all values from a POST submission right into the PHP script.
As per PHP documentation,
$_POST is an associative array of variables passed to the current script via the HTTP POST method.
Let‘s break this definition down:
- Associative Array: The data is stored as array elements for easy access
- Variables: Contains user-input from form fields and upload data
- HTTP POST method: Values that were transmitted via a POST request
PHP populates the $_POST array automatically when a form with method="post" is submitted.
For example, this contact form:
<form method="post" action="contact.php">
<input name="name">
<input name="email">
<button type="submit">Send</button>
</form>
Can have its values referenced in PHP like:
$_POST[‘name‘]; // contains name input
$_POST[‘email‘]; // contains email input
The key things to note are:
- Array indexes match form input names
- Works only for POST requests
- Can access values without extra parsing
This simplicity of the $_POST variable makes POST submissions easy to handle in PHP.
Why POST Trumps GET
While POST and GET can both pass form information to scripts, POST has definitive advantages that have led to widespread adoption.
POST Prevents Data Leaks
GET requests append the form values right to the URL in plain sight. This causes inadvertent data leaks if the user shares URLs.
POST keeps the payload tucked away in HTTP headers safely out of sight. So no accidental leaks.
Bigger Data Transfers
GET request URLs have size limitations depending on browsers and web servers. POST bypasses this by handling data as a raw HTTP message stream without constraints.
This means large file uploads are only possible via POST.
Binary Data Support
While GET can only handle text, POST supports binary formats like images, excel sheets, pdfs etc.
This enables file uploads from mobile, desktop and web apps via multi-part POST encoding.
According to Strapi‘s 2022 developer survey, 82% of developers are actively using POST compared to 75% using GET requests. The advantages have led POST to gain mainstream adoption.
Key POST Security Considerations
POST variables may simplify form processing, but also open up attack vectors that can compromise your whole application.
Let‘s explore crucial security best practices.
#1: Validate & Sanitize Input
Never trust any data coming in via POST. Always verify and sanitize every value:
$email = sanitize_email($_POST[‘email‘]);
$age = filter_var($_POST[‘age‘], FILTER_VALIDATE_INT);
This eliminates foul input that could break your SQL queries or allow code injection attacks.
#2: Use Parameterized Queries
Avoid concatenating raw POST data in database queries:
// Dangerous raw POST variable usage in SQL
$sql = "SELECT * FROM users WHERE email = {$_POST[‘email‘]}";
Instead use prepared parameterized queries:
$stmt = $db->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param(‘s‘, $_POST[‘email‘]); // ‘s‘ specifies string binding
$stmt->execute();
This is vital to block SQL injection attempts.
#3: Hash Passwords
If your form handles passwords or other highly sensitive data, hash them before storage:
$password = password_hash($_POST[‘password‘], PASSWORD_DEFAULT);
Always hash passwords as a crucial safety step according to OWASP guidelines.
#4: Address Mass Assignment
The mass assignment risk appears when POST variables directly populate columns without selectivity:
//Dangerous direct POST usage in queries
insertIntoUsers($_POST);
// Attacker can inject malicious fields!
$_POST[‘is_admin‘] = true;
Practice selective binding like:
$username = $_POST[‘username‘];
$password = $_POST[‘password‘];
insertIntoUsers($username, $password);
These best practices will help reinforce your POST variable handling.
POST Usage Examples
Let‘s explore some practical examples of using POST variables in PHP for common scenarios.
Contact Form
A simple contact form can process messages using POST:
$name = $_POST[‘name‘];
$email = $_POST[‘email‘];
$message = $_POST[‘message‘];
// Validation checks
$to = "contact@mydomain.com";
$subject = $name . " sent a message";
$body = $message;
mail($to, $subject, $body);
The POST values are directly accessed to process the form input with email sending.
Registration System
Secure registration forms help prevent account abuse. Validate and hash the password upon new signups:
$username = sanitize_string($_POST[‘username‘]);
$email = sanitize_email($_POST[‘email‘]);
$password = password_hash($_POST[‘password‘], PASSWORD_DEFAULT);
$query = "INSERT INTO users
(username, email, password)
VALUES(?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param(‘sss‘, $username, $email, $password);
$stmt->execute();
This safely handles registration POST data as per security best practices.
Image Upload Script
To securely handle image uploads via POST:
$image_name = $_FILES[‘image‘][‘name‘];
$tmp_name = $_FILES[‘image‘][‘tmp_name‘];
$img_error = $_FILES[‘image‘][‘error‘];
if ($img_error === 0) {
$img_ex = pathinfo($image_name, PATHINFO_EXTENSION);
$image_name = uniqid() . "." . $img_ex;
move_uploaded_file($tmp_name, "/uploads/$image_name");
} else {
exit("Image upload failed with error $img_error");
}
This example handles the uploaded file data properly using temporary names, extensions, unique filenames and move operations.
These examples showcase practical usages of POST variables in PHP for sending data.
POST vs. GET – A Direct Comparison
While this guide focuses on POST handling, the age old POST vs GET debate always comes up. Let‘s compare them across key parameters:
| Basis | POST | GET |
|---|---|---|
| Data Visibility | Not exposed as request is in HTTP headers | Appended to URL so data is visible |
| Idempotence | Repeated identical requests may have side effects | Idempotent as making same request has no extra effect |
| Caching | Not cacheable | Can be cached for improved performance |
| Data Length | No size limits typically | Limited to 2048 characters by specification |
| Bookmarkability | URLs do not capture content | URLs capture query data for bookmarking |
| Security | More secure as data not shown | Risk of accidental data leakage via URLs |
In summary,
- Use POST when you need security, bigger data, caching avoidance
- Use GET for public visibility, idempotency and bookmarking needs
Understand the strengths of each method to make the right choice.
Expert Recommendations
As per PHP documentation conventions, accessing raw POST arrays directly is risky without prior sanitization or validation.
Top developers recommend:
Escape Output
echo htmlspecialchars($_POST[‘input‘]);
This prevents XSS attacks by escaping HTML entities.
Cast Expected Types
$age = (int)$_POST[‘age‘]; // integer
Cast expected data types. Helps catch issues.
Define Expected Fields
$expected = [‘name‘,‘email‘];
Specify anticipated fields during validation to restrict unauthorized inserts.
Use Filter Functions
$email = filter_var($input, FILTER_SANITIZE_EMAIL);
Inbuilt filters sanitize data according to rules for convenience.
These tips follow best practices stated by PHP experts like PHP The Right Way.
When Not To Use POST?
POST is not suited for every use case because of its restrictions. Avoid POST when:
Caching Is Needed
POST requests are not cached by browsers or proxies by default for safety. Use GET if response caching is required.
Public Linking Needed
As POST data is not visible, it cannot be bookmarked or publicized the same way GET parameters in a URL can.
Idempotency Required
Repeated identical POST requests can have unexpected side effects on the server-side. GET ensures same call is safe.
APIs For Read Operations
APIs that simply query data can leverage GET requests for visibility. POST implies write operations.
These limitations are worth noting for making optimal architectural choices.
Conclusion
POST variables form the backbone of form processing in PHP-based systems. This comprehensive guide provided both conceptual foundations and actionable techniques to master POST handling by covering:
- Definition of the $_POST variable
- Benefits over GET that enabled mainstream adoption
- Vital security best practices
- Practical usage examples
- Comparison with GET method tradeoffs
- Expert recommendations
With the phenomenal dominance of WordPress, Laravel and millions of PHP sites, understanding POST data is crucial for any back-end professional.
I hope this guide helped you grasp all key aspects of processing POST submissions to create robust applications. The principles broadly apply also to frameworks like Codeigniter and Symfony that internally handle variables.
Whether you are an expert developer or just starting out, do share any other POST handling tips that have served you well!


