This tutorial explains how to handle form data submitted via the GET method in PHP. The GET method is commonly used to retrieve data from the server and is typically used for search forms.
PHP Form Data GET Method Tutorial
1. Creating a Simple Form
Below is an example of a simple form that collects a user's name and email address:
<form method="GET" action="process_form.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
This form uses the GET
method to send data to process_form.php
.
2. Processing Form Data in PHP
In the process_form.php
file, you can access the submitted data using the $_GET
superglobal:
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// Collect and sanitize form data
$name = htmlspecialchars(trim($_GET['name']));
$email = htmlspecialchars(trim($_GET['email']));
// Display the submitted data
echo "Name: " . $name . " ";
echo "Email: " . $email . " ";
}
Here, we first check if the request method is GET, then retrieve the data from the $_GET
array. We also sanitize the inputs using htmlspecialchars
and trim
to avoid XSS attacks and unnecessary whitespace.
3. Validating Form Data
It's important to validate the data received from the form. You can perform simple validation like checking if the fields are empty:
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = htmlspecialchars(trim($_GET['name']));
$email = htmlspecialchars(trim($_GET['email']));
if (empty($name) || empty($email)) {
echo "Please fill in all fields.";
} else {
echo "Name: " . $name . " ";
echo "Email: " . $email . " ";
}
}
This example checks if either the name or email field is empty and displays an error message if so.
4. Conclusion
The GET method is useful for sending data that is not sensitive, as the data is appended to the URL. Always remember to validate and sanitize user inputs to ensure the security and integrity of your application.