Loading...
Loading...

PHP Form Data GET Method Tutorial

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.

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.

0 Interaction
1.1K Views
Views
22 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home