Hello! Welcome to the next lesson in our PHP Fundamentals Refresher.
In our last lesson, we explored arrays, learning how to store multiple values in a single variable. This was a crucial step, as you're about to see how PHP uses arrays to handle one of the most fundamental parts of web development: user input.
Today's lesson focuses on how to handle form data using GET and POST methods. This is the bridge between a static HTML page and a dynamic PHP application. Every time you log in to a website, submit a comment, or use a search bar, you're interacting with a form. We'll explore how PHP captures this data and makes it available for you to process. This skill is essential for your goal of building full web applications.
1. The Form Handling Process: An Overview
Before diving into the code, let's look at the big picture. A user fills out an HTML form and clicks "submit." The browser then packages the data and sends it to a web server where your PHP script lives. Your script receives the data and can then do something with it, like saving it to a database or displaying it back to the user.
The two key components of the HTML <form> tag that control this process are the action and method attributes:
action: Specifies the URL of the PHP script that will process the form data.method: Specifies the HTTP method to use when sending the data. The two most common methods areGETandPOST.
2. The POST Method: Secure and Robust
The POST method is the standard choice for most forms, especially those involving sensitive information like passwords or personal details. When you use POST, the form data is sent in the body of the HTTP request, meaning it's not visible in the browser's URL bar.
When a form is submitted via POST, PHP automatically populates a special superglobal variable called $_POST. This variable is an associative array, where the keys are the name attributes of your form's input fields, and the values are the data entered by the user. This is a direct application of what we learned in the last lesson!
To see how this works, let's watch a short video that introduces the POST method.
PHP $_GET and $_POST explained
This video from Bro Code will quickly demonstrate how to set up a form with the POST method and how to access the submitted data in PHP using the $_POST superglobal array.
First, watch from 00:34 to 02:33 to see the creation of a simple HTML form. Then, skip to 05:28 and watch until 06:15 to understand how the POST method works and why it's more secure.
As you saw, using POST keeps user data hidden from the URL, which is a fundamental security practice.
3. The GET Method: Data in the URL
The GET method works differently. It bundles the form data into a query string and appends it directly to the URL specified in the action attribute.
http://example.com/search.php?term=php&category=tutorials
While this makes the data visible (and therefore insecure for sensitive information), it's useful for things like search queries or filter settings, where you might want the user to be able to bookmark or share the URL with the parameters included.
When a form is submitted using GET, PHP populates the $_GET superglobal associative array.
Data collection with PHP - Creating forms, Setting up and Validation
The following article from talent500.com provides a clear, text-based explanation of the GET and POST methods with simple code examples.
Read the sections titled 'GET METHOD' and 'POST METHOD'. Pay close attention to the example code and how the URL looks after submitting the form with the GET method.
When to Use GET vs. POST
Use POST When... |
Use GET When... |
|---|---|
| Submitting sensitive data (passwords, etc.) | Creating a search page. |
| The data size is large. | You want to bookmark the page with results. |
| You are changing data on the server (creating, updating, deleting). | The request is idempotent (repeating it has no side effects). |
Test your understanding!
You are building two forms:
- A user login form with fields for
usernameandpassword. - A search form for a blog with a single field for
search_query.
Which method (GET or POST) should you use for each form, and why?
Show answer
- Login Form: Use
POST. The form contains a sensitive password that should not be visible in the URL, browser history, or server logs. - Search Form: Use
GET. The search query is not sensitive. UsingGETallows users to bookmark the search results page or share the URL with others, which will re-execute the same search.
4. Secure Form Processing: A Step-by-Step Guide
Simply grabbing data from $_POST and using it is dangerous. Your highest priority when handling user input is security. You must assume all user data is potentially malicious. Let's walk through the essential steps to process form data securely.
This next video is incredibly valuable. It covers not just how to handle form data, but how to do it safely.
6 | The Basics of PHP Form Handling Tutorial | 2023 | Learn PHP Full Course for Beginners
This video from Dani Krossing provides a detailed walkthrough of secure form handling. We will break it down into key security practices.
We'll go through this in two parts. First, watch from 07:13 to 14:05. This covers two critical concepts: Checking the Request Method: Using $_SERVER['REQUEST_METHOD'] to ensure the script was accessed via a form submission. Sanitizing Output: Using htmlspecialchars() to prevent Cross-Site Scripting (XSS) attacks by converting special characters into HTML entities. Then, watch from 19:04 to 23:12. This part brilliantly demonstrates why client-side validation (like the required attribute) is not enough for security and why you must perform server-side validation using functions like empty().
Let's summarize those crucial security steps:
-
Verify the Request Method: Always wrap your processing logic in a condition to ensure the data was sent using the expected method. This prevents users from accessing your processing script directly.
if ($_SERVER["REQUEST_METHOD"] == "POST") { // Process form data here... } -
Validate on the Server: Never trust client-side validation. As the video showed, it can be easily bypassed. Always re-validate the data on the server. A simple first step is checking if required fields are empty.
if (empty($_POST["username"])) { // Handle the error - username is required. } -
Sanitize for Output: To prevent Cross-Site Scripting (XSS), where an attacker injects malicious scripts into your webpage, you must escape any user-provided data before you display it. The
htmlspecialchars()function is your primary tool for this.$username = htmlspecialchars($_POST["username"]); echo "Welcome, " . $username; // Now it's safe to display
Test your understanding!
You have a comment section on your blog. The following PHP code retrieves and displays a comment submitted via a POST request:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment = $_POST['comment_text'];
echo "<div class='comment'>" . $comment . "</div>";
}
?>
What is the security vulnerability in this code? How would you fix it?
Show answer
The vulnerability is Cross-Site Scripting (XSS). An attacker could submit a comment containing a <script> tag (e.g., <script>alert('hacked');</script>). Since the code directly echos the raw input, the browser would execute that script.
The fix is to use htmlspecialchars() to sanitize the input before displaying it:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment_text = htmlspecialchars($_POST['comment_text']);
echo "<div class='comment'>" . $comment_text . "</div>";
}
?>
This converts characters like < and > into their HTML entity equivalents (< and >), which the browser will display as text instead of interpreting as code.
5. Redirecting After Submission
After successfully processing a form (e.g., saving data to a database), it's bad practice to leave the user on the processing script page. If they refresh the page, the browser might try to resubmit the form data.
The standard solution is to redirect the user to another page (like a "thank you" page or back to the homepage) using the header() function.
6 | The Basics of PHP Form Handling Tutorial | 2023 | Learn PHP Full Course for Beginners
This final clip from the same video by Dani Krossing demonstrates how to use the header() function to redirect a user after the form has been processed.
Watch from 17:29 to 19:04. Notice how the header('Location: ...') call sends the user to a new page, providing a much better user experience.
Important Note: You must call the header() function before any HTML or echo output is sent to the browser.
Conclusion
You have now learned one of the most practical and essential skills in PHP. By understanding how to handle form data, you've unlocked the ability to create interactive web applications that respond to user input.
Key Takeaways:
- HTML forms use
actionto specify a processing script andmethod(GETorPOST) to define how data is sent. - The
POSTmethod is the standard for submitting data, as it's more secure and has no size limit. Data is available in the$_POSTassociative array. - The
GETmethod sends data in the URL and is suitable for non-sensitive data like search queries. Data is available in the$_GETarray. - Security is paramount: Always verify the request method, validate input on the server, and sanitize output with
htmlspecialchars()to prevent XSS attacks. - Use
header('Location: ...')to redirect users after a successful form submission to prevent duplicate submissions.
In our next lesson, we will learn about including and requiring PHP files. This will allow us to separate our HTML form markup from our PHP processing logic, a crucial step towards organizing your code for larger projects and building a clean application architecture.