Accessing Form Data with $_GET and $_POST
Learning Objectives
- Master PHP loop structures
- Choose appropriate loop types
- Control loop execution flow
- Optimize loop performance
Understanding PHP Superglobals for Form Data
One of PHP's most powerful features is its ability to easily access data submitted through HTML forms. PHP makes this data available through special predefined arrays called "superglobals." In this lecture, we'll focus on the two superglobals most commonly used for form data: $_GET and $_POST.
The Mailroom Analogy
Think of PHP as a mailroom in a large office building:
- $_GET is like the public bulletin board where messages are posted for everyone to see. It's accessible, visible, and limited in size.
- $_POST is like the secure internal mail system where sealed envelopes are delivered directly to the recipient. It's more private and can handle larger messages.
- The PHP processor is like the mail clerk who sorts incoming messages and makes them available to the correct department (your script).
- Form fields are like the different parts of a form letter or package – each with its own label and content.
Introduction to PHP Superglobals
Superglobals are special predefined arrays in PHP that are always accessible, regardless of scope. They contain data from various sources.
PHP's Superglobal Arrays
| Superglobal | Contains | Form Relevance |
|---|---|---|
$_GET |
Data sent through URL parameters | Data from forms with method="get" |
$_POST |
Data sent through HTTP POST method | Data from forms with method="post" |
$_REQUEST |
Combined data from $_GET, $_POST, and $_COOKIE | Can access form data regardless of method (not recommended) |
$_FILES |
Information about uploaded files | Used for file upload forms |
$_SERVER |
Server and execution environment information | Contains REQUEST_METHOD to check form submission method |
$_ENV |
Environment variables | Limited form relevance |
$_COOKIE |
HTTP cookie values | Can store form preferences or session data |
$_SESSION |
Session variables | Can store form data across multiple pages |
Accessing Data with $_GET
The $_GET superglobal array contains all variables sent to the script through URL parameters. These parameters are visible in the browser's address bar.
Basic $_GET Access
###CODE_BLOCK_11###
When the form is submitted, the URL might look like:
search.php?query=wordpress+themes&category=products
Handling Array Data in $_GET
HTML forms can send array data by using square brackets in the field names.
###CODE_BLOCK_13###
The resulting URL might look like:
process_filter.php?categories[]=electronics&categories[]=books&price[min]=10&price[max]=100
Parsing GET URLs Manually
Sometimes you might need to work with URL parameters directly:
###CODE_BLOCK_15###
Accessing Data with $_POST
The $_POST superglobal array contains all variables sent to the script through the HTTP POST method. These values are not visible in the URL.
Basic $_POST Access
###CODE_BLOCK_17###
Handling Complex Form Data with $_POST
POST can handle more complex data structures, including nested arrays and multi-dimensional data.
###CODE_BLOCK_18###
Accessing Nested Form Data
Checking for Form Data Existence
One of the most critical aspects of handling form data is checking whether values exist before trying to use them. PHP provides several functions for this purpose.
Methods for Checking Data Existence
| Method | Description | Example |
|---|---|---|
isset() |
Checks if a variable is set and not null | if (isset($_POST['username'])) { ... } |
empty() |
Checks if a variable is empty (null, 0, false, empty string, etc.) | if (!empty($_GET['query'])) { ... } |
array_key_exists() |
Checks if a specific key exists in an array | if (array_key_exists('email', $_POST)) { ... } |
| Null coalescing operator (??) | Returns the right operand if the left is null | $username = $_POST['username'] ?? 'Guest'; |
| Checking REQUEST_METHOD | Verifies the form submission method | if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... } |
Existence Checking Examples
###CODE_BLOCK_27###
Checking Existence of Array Elements
###CODE_BLOCK_28###
Filtering and Sanitizing Form Data
Before using form data, it's crucial to properly filter and sanitize it to prevent security issues like XSS attacks or SQL injection.
Basic Sanitization Methods
| Function | Purpose | Example |
|---|---|---|
htmlspecialchars() |
Convert special characters to HTML entities | $safe_text = htmlspecialchars($_POST['comment']); |
strip_tags() |
Remove HTML and PHP tags | $no_html = strip_tags($_POST['input']); |
filter_var() |
Filter a variable with a specified filter | $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); |
filter_input() |
Get and filter input from a superglobal | $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); |
mysqli_real_escape_string() |
Escape SQL injection in strings (for MySQLi) | $safe_input = mysqli_real_escape_string($conn, $input); |
trim() |
Remove whitespace from beginning and end | $username = trim($_POST['username']); |
Using Filter Functions
###CODE_BLOCK_41###
Practical Sanitization Example
###CODE_BLOCK_42###
Handling Special Types of Form Data
Different form field types require special handling techniques beyond basic text fields.
Handling Checkboxes
Checkboxes have a unique behavior: they only appear in $_POST or $_GET when checked.
###CODE_BLOCK_43###
Handling Radio Buttons
###CODE_BLOCK_44###
Handling Select Dropdowns
###CODE_BLOCK_45###
Handling Date and Time Inputs
###CODE_BLOCK_46###
Redirecting After Form Processing
After processing form data, it's often good practice to redirect the user to another page to prevent form resubmission.
POST-Redirect-GET Pattern
###CODE_BLOCK_47###
Common Patterns for Form Processing
Here are some common patterns and best practices for processing form data in PHP applications.
Self-Processing Form
###CODE_BLOCK_48###
Form Handler Class
###CODE_BLOCK_49###
Security Best Practices for Form Data
Handling form data securely is essential for protecting your applications and users.
Key Security Considerations
- Always validate and sanitize all input: Never trust user input, even if you have client-side validation.
- Use prepared statements for database queries: Prevent SQL injection attacks.
- Implement CSRF protection: Prevent Cross-Site Request Forgery attacks.
- Validate file uploads carefully: Check file types, sizes, and content.
- Use HTTPS: Encrypt form data in transit.
- Be cautious with $_REQUEST: It combines $_GET, $_POST, and $_COOKIE, which can lead to unexpected behavior.
- Validate data types: Ensure numbers are numbers, emails are emails, etc.
- Handle errors gracefully: Don't expose technical details to users.
CSRF Protection Example
###CODE_BLOCK_50###
Debugging Form Data
When working with form data, debugging techniques can help you identify and fix issues quickly.
Viewing Form Data Contents
###CODE_BLOCK_51###
Logging Form Submissions
###CODE_BLOCK_52###
Common Issues and Solutions
| Issue | Possible Cause | Solution |
|---|---|---|
| Empty $_POST array | Form method is set to "get" instead of "post" | Check the form's method attribute |
| Missing field in $_POST | Field name is misspelled or not set in the form | Verify field names match exactly between HTML and PHP |
| Array expected but string received | Missing square brackets in input name | Use name="field[]" for arrays |
| Form resets after submission | Page is refreshing without preserving input | Use sessions to store form data or use self-processing form pattern |
| File uploads not working | Missing enctype="multipart/form-data" on form | Add proper enctype attribute to the form |
| Special characters corrupted | Character encoding issues | Set proper content-type headers and use htmlspecialchars |
| "Undefined array key" notice | Trying to access a non-existent array key | Use isset() or the null coalescing operator (??) |
Working with Form Data in WordPress
WordPress provides several functions and security features for handling form data.
WordPress Sanitization Functions
| Function | Purpose | Example |
|---|---|---|
sanitize_text_field() |
Sanitizes text input | $name = sanitize_text_field($_POST['name']); |
sanitize_email() |
Sanitizes email address | $email = sanitize_email($_POST['email']); |
sanitize_title() |
Sanitizes string for use in URL or slug | $slug = sanitize_title($_POST['title']); |
absint() |
Converts to positive integer | $id = absint($_GET['id']); |
wp_kses() |
Allows specific HTML tags | $content = wp_kses($_POST['content'], $allowed_html); |
Handling Form Submissions in WordPress
###CODE_BLOCK_63###
AJAX Form Handling in WordPress
###CODE_BLOCK_64###
Homework: Form Data Processing
Complete the following exercises to practice accessing and processing form data with PHP.
Task 1: Basic Form Processing
Create a registration form with the following fields:
- Full Name (text input)
- Email Address (email input)
- Password (password input)
- Confirm Password (password input)
- Date of Birth (date input)
- Gender (radio buttons)
- Interests (multiple checkboxes)
- Country (select dropdown)
Then create a PHP script that:
- Processes the form when submitted
- Validates all fields (required fields, matching passwords, valid email, etc.)
- Displays appropriate error messages
- If all validation passes, displays a success message with all the submitted data
Task 2: Self-Processing Form with Data Persistence
Create a self-processing form that:
- Displays and processes the form in the same PHP file
- Preserves user input when validation fails (the form should be pre-filled with previous entries)
- Implements proper sanitization for all fields
- Includes at least one field of each type: text, checkbox, radio, select, and textarea
Task 3: Advanced Array Handling
Create a form that collects the following information:
- Personal Information (name, email)
- Multiple addresses (home and work) with street, city, state, and zip for each
- Education history (multiple schools with name, year, and degree)
Use nested arrays in your form fields and demonstrate how to:
- Structure the HTML form with proper array notation
- Access and validate the nested data in PHP
- Display the processed data in a formatted way
Bonus Challenge: Create a Multi-Step Form
Create a multi-step form that:
- Spans across 3 different pages/steps
- Uses sessions to store data between steps
- Allows users to go back to previous steps and edit data
- Shows a final confirmation page with all data for review
- Processes all data only after final confirmation