Processing user input is pivotal for web apps. As a full-stack developer with over a decade of PHP experience, the superglobals $_GET and $_POST are indispensable weapons in my coding arsenal for secure form handling. Mastering them is a must for any professional.
Let‘s analyze them in-depth, so you can utilize these arrays like a seasoned pro.
The Critical Role of User Input Validation
Validating and sanitizing input is no casual task. According to Acunetix, over 70% of web app vulnerabilities occur due to faulty user input handling.
XSS attacks, SQL injections, and request forgeries can all strike apps without rigorous validation defenses. I constantly see startups and mature companies alike fall victim to these bugs causing massive disruptions.
Input mistakes also ranked as the #1 source of reported breaches in 2022 according to Verizon‘s data breach report.
So before diving into usage of $_GET and $_POST, let‘s build a solid foundation on validation techniques.
Core Validation Defenses
Here are essential validation and sanitization methods I use on all inbound data:
Filter Functions – The filter extension has functions like filter_var(), filter_input() for sanitizing data types like emails, URLs, integers etc.
Type Casting – Use (int), (float) and other casts to convert input to expected types
Data Trimming – Trim extra whitespace with trim()
Input Length Checks – Validate string lengths match expected ranges
Regular Expressions – Powerful for validating complex textual input patterns
Escaping – Escape special characters to prevent SQLi, XSS attacks etc
CSRF Tokens – Required for $_POST forms to prevent request forgeries
And much more. Combining techniques is key for airtight security.
On top of this, using prepared parameterized statements when inserting data into databases is mandatory for preventing SQL injection vulnerabilities.
Never ever directly insert unsanitized $_POST or $_GET data into a database.
With these fundamentals established, let‘s unpack $_GET and $_POST specifically.
An Overview of $_GET and $_POST
Both $_GET and $_POST are PHP superglobal arrays containing user input data from form submissions. Key distinctions:
$_GET
- Submitted via the URL query string
- Values are visible and exposed in URL
- Limited in amount of data by max URL size
- Best for non-sensitive public data
$_POST
- Submitted through the POST request method
- Values NOT visible in URL
- Can handle large amounts of data
- Suitable for sensitive, private data
Bottom line: $_GET is for general public data, $_POST for sensitive transmissions.
Validating and Sanitizing $_GET Input
Since $_GET values originate from user input and are visible client-side, seriously validate them.
Here‘s a standard check I perform:
$username = ‘‘;
if (isset($_GET[‘username‘])) {
$username = $_GET[‘username‘];
// Filter/sanitize
$username = filter_var($username, FILTER_SANITIZE_STRING);
// Ensure not empty
if (!empty($username)) {
// Additional length check
if (strlen($username) > 50)) {
die(‘Invalid username‘);
}
} else {
die(‘No username supplied‘);
}
}
This filters the value, checks for emptiness, verifies the character length is under 50, and fails if any check fails.
Similar validation should be done on ALL $_GET variables before usage in code. Garbage in, garbage out.
Avoiding GET Parameter Manipulation
Since $_GET values are visible in the URL, users could potentially manipulate them for malicious reasons.
For example, if a "file" parameter is used to specify a file for downloading like:
http://example.com/download.php?file=report123.pdf
A hacker could modify the GET parameters to try and access other files:
http://example.com/download.php?file=../config.php
This is why input validation on GET parameters is so vital. Never trust the incoming data.
Additionally, tokenizing "random" GET parameters can prevent tampering like only allowing properly signed download URLs.
Submitting Forms with $_GET
$_GET is handy for search forms, surveys, public inquiry forms, etc where sensitive data is NOT involved.
<form method="GET" action="search.php">
<input type="text" name="query">
<select name="category">
<option value="articles">Articles</option>
</select>
<input type="submit" value="Search">
</form>
The page search.php can now access the query and chosen category via $_GET[‘query‘] and $_GET[‘category‘]. Easy!
This data can be validated and used for a search implementation without worrying about sensitive exposures.
Handling Larger Submissions with $_POST
For anything with private data, variable lengths, or file uploads, I switch to using $_POST for submissions.
A user registration form is a prime example:
<form method="POST" action="register.php" enctype="multipart/form-data">
<input type="email" name="email">
<input type="password" name="password">
<input type="file" name="avatar">
<textarea name="biography"></textarea>
<input type="submit" value="Register">
</form>
Now all this data can be processed in PHP securely:
$email = $_POST[‘email‘];
$password = $_POST[‘password‘];
$biography = $_POST[‘biography‘];
// Insert account with $email, hashed $password etc
No sensitive info gets exposed in transit. Much better!
This applies for admin systems, multi-page form workflows, or anywhere private data is being transmitted.
Advanced File Uploading Handling
A common upload usage is:
$file = $_FILES[‘upload‘][‘tmp_name‘];
// Validate file, then move to permanent home
move_uploaded_file($file, "/uploads/".$_FILES[‘upload‘][‘name‘])
However, this has potential vulnerabilities if not handled properly:
- File path manipulation
- Inline image PHP uploads
- XML attachment issues
- Unchecked file sizes/types
That‘s why hardened validation is critical:
$max_size = 2 * 1024 * 1024; // 2MB
$valid_types = [‘image/jpeg‘, ‘image/png‘]; // Set allowed MIME types
$info = getimagesize($_FILES[‘upload‘][‘tmp_name‘]); // Must be valid image
if ($_FILES[‘upload‘][‘size‘] > $max_size) {
die("File too large");
}
if (!in_array($_FILES[‘upload‘][‘type‘], $valid_types)) {
die("Invalid file type");
}
// Ensure unique filename then upload securely
$name = uniqid().$_FILES[‘upload‘][‘name‘];
move_uploaded_file($_FILES[‘upload‘][‘tmp_name‘], "./uploads/$name");
Input validation is always priority #1, even for uploads!
Combining $_GET and $_POST
$_GET and $_POST can be mixed within the same script:
// Fetch category filter from GET
$category = $_GET[‘category‘];
// Handle form submission via POST
$name = $_POST[‘name‘];
$email = $_POST[‘email‘];
// Register user in $category group
registerUser($name, $email, $category);
This demonstrates the distinction of GET parameters for public inputs, while POST handles the sensitive submission.
Comparison to Other Input Methods
While $_GET and $_POST are most common, other submission methods exist:
AJAX – Async JavaScript requests. Useful for dynamic apps.
Cookies – Persistent client storage for saved preferences.
Headers – Pass custom $_SERVER headers to scripts.
CLI – Handle command line arguments to scripts.
Each excels in different contexts. Security still demands rigorous validation no matter the input type.
Applying $_GET and $_POST For Security and Scale
Once the fundamentals are mastered, skillfully applying $_GET and $_POST paves the way for robust apps.
Here are some useful applications:
- Account Systems – Securely handle registration and login flows with
$_POST - Multi-Step Workflows – Pass data between wizard steps safely using POST
- Dynamic Search – Filter results via
$_GETparameters - Form Handling APIs – Create endpoints to handle submissions in apps
- Analytics – Track page events by logging requests
- Admin Dashboards – Use POST for actions like content imports or deletions for extra security
And many more use cases. Thinking critically about when to leverage GET or POST strengthens both design and security.
Key Takeaways
Working with forms is integral to web development. Learning to properly handle input requires forethought and rigor.
$_GET and $_POST provide the basic tools for processing submissions, but should never be used without comprehensive validation.
After over a decade developing PHP apps, my top advice is:
- Never ever trust raw user input!
- Implement layered defenses like filtering, escaping etc
- Validate file uploads cautiously
- Use prepared statements for database interactions
- Follow other security best practices
Attention to detail here radically minimizes exploit risks while wielding the true potential of these arrays.
So sharpen those programming skills and let no vulnerabilities slip through the cracks of your validations. Handling user data securely allows building the robust web apps of tomorrow. The power lies in your hands…and code!


