Paramclasses Academy - Blog

Tutorials Details

Form Handling in PHP Using GET and POST With Practical Examples

Form Handling in PHP Using GET and POST With Practical Examples

October 10, 2026

Meta Title: PHP Form Handling Tutorial for Beginners – GET & POST

Meta Description: Learn PHP form handling using GET and POST methods, form validation, sanitization, and practical examples with a student registration form.

Focus Keyword: PHP Form Handling Tutorial for Beginners

Secondary Keywords: PHP GET Method, PHP POST Method, PHP Form Validation, PHP Form Handling Examples, PHP Registration Form, PHP Input Validation, Core PHP Tutorial

Suggested URL Slug: php-form-handling-tutorial

Introduction to Form Handling in PHP

Welcome to Module 8 of our Core PHP Programming Tutorial for Beginners.

In previous modules, we learned PHP variables, data types, operators, conditional statements, loops, arrays, strings, and functions.

In this module, we will learn how to collect information from users through HTML forms and process that information using PHP.

Forms are an essential part of modern websites. Whenever you register an account, log in to a website, contact a business, search for a product, or submit an application, you interact with a form.

PHP allows developers to receive submitted form data, validate user input, process information, and display appropriate responses.

By the end of this tutorial, you will understand the GET and POST methods and know how to create practical PHP forms.

1. What Is Form Handling in PHP?

Form handling is the process of collecting information entered by users into an HTML form and processing that information using PHP.

For example, a student registration form might collect:

  • Student name

  • Email address

  • Mobile number

  • Course name

  • City

PHP receives the submitted information and can validate it, display a confirmation message, or save it to a database.

How PHP Form Handling Works

  1. A user opens a webpage containing an HTML form.

  2. The user enters information into the form fields.

  3. The user clicks the Submit button.

  4. The browser sends the submitted data to a PHP script.

  5. PHP validates and processes the data.

  6. The server returns a response to the browser.

Real-world example: On an online course website, a student enters their name and email address. PHP validates the information and processes the registration.

2. What Is an HTML Form?

An HTML form is used to collect information from website visitors.

The HTML form element commonly uses these attributes:

  • action: Specifies the URL or PHP file that processes the form.

  • method: Specifies how the browser submits the form, commonly GET or POST.

  • name: Identifies a field or form element.

  • type: Defines the kind of input, such as text, email, or password.

Example: Simple HTML Form

Create a file named form.html.

<!DOCTYPE html>
<html>
<head>
    <title>Simple PHP Form</title>
</head>
<body>

    <h2>Student Information</h2>

    <form action="process.php" method="post">
        <label for="name">Student Name:</label>
        <input type="text" id="name" name="name" required>

        <br><br>

        <label for="email">Email Address:</label>
        <input type="email" id="email" name="email" required>

        <br><br>

        <button type="submit">Submit</button>
    </form>

</body>
</html>

The form sends the submitted values to process.php using the POST method.

The name attribute is important because PHP uses these field names to access the submitted data.

3. What Is the GET Method in PHP?

The GET method submits form data through URL query parameters.

For example, a search form might generate a URL like this:

search.php?keyword=php

PHP can access these query parameters through the $_GET superglobal array.

Example: Form Using GET

Create a file named get-form.php.

<!DOCTYPE html>
<html>
<head>
    <title>PHP GET Example</title>
</head>
<body>

    <h2>Search Form</h2>

    <form action="" method="get">
        <label for="keyword">Enter Keyword:</label>

        <input
            type="text"
            id="keyword"
            name="keyword"
            required
        >

        <button type="submit">Search</button>
    </form>

    <?php
    if (isset($_GET["keyword"])) {
        $keyword = trim($_GET["keyword"]);

        echo "<p>You searched for: " .
            htmlspecialchars($keyword, ENT_QUOTES, "UTF-8") .
            "</p>";
    }
    ?>

</body>
</html>

Example Output

If the user enters PHP Tutorial, the browser URL may look like:

get-form.php?keyword=PHP+Tutorial

The page displays:

You searched for: PHP Tutorial

Explanation

  • method="get" submits the form using GET.

  • $_GET["keyword"] accesses the submitted query parameter.

  • isset() checks whether the parameter exists.

  • trim() removes leading and trailing whitespace.

  • htmlspecialchars() escapes special HTML characters before displaying the value.

Real-World Applications of GET

GET is commonly used for:

  • Search forms

  • Product filters

  • Pagination

  • Category selection

  • Sorting products

  • Shareable search results

Important: GET data can appear in the URL, browser history, and server logs. Do not use GET for passwords or sensitive information. GET should generally be used for operations that retrieve information rather than change server-side data.

4. What Is the POST Method in PHP?

The POST method submits form data in the HTTP request body rather than placing the submitted fields in the URL query string.

PHP accesses submitted POST fields using the $_POST superglobal array.

POST is commonly used for registration forms, contact forms, login forms, and other submissions that create or update information.

POST does not automatically encrypt data. Use HTTPS to protect data in transit.

Example: Form Using POST

Create a file named post-form.php.

<!DOCTYPE html>
<html>
<head>
    <title>PHP POST Example</title>
</head>
<body>

    <h2>Student Registration</h2>

    <form action="" method="post">
        <label for="name">Student Name:</label>
        <input
            type="text"
            id="name"
            name="name"
            required
        >

        <br><br>

        <label for="course">Course:</label>
        <input
            type="text"
            id="course"
            name="course"
            required
        >

        <br><br>

        <button type="submit">Register</button>
    </form>

    <?php
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $name = trim($_POST["name"] ?? "");
        $course = trim($_POST["course"] ?? "");

        if ($name === "" || $course === "") {
            echo "<p>Please complete all fields.</p>";
        } else {
            echo "<h3>Registration Details</h3>";

            echo "Name: " .
                htmlspecialchars($name, ENT_QUOTES, "UTF-8") .
                "<br>";

            echo "Course: " .
                htmlspecialchars($course, ENT_QUOTES, "UTF-8");
        }
    }
    ?>

</body>
</html>

Example Output

If a user enters:

  • Student Name: Rahul Sharma

  • Course: BCA

The page displays:

Registration Details

Name: Rahul Sharma

Course: BCA

Explanation

  • method="post" submits the form using POST.

  • $_SERVER["REQUEST_METHOD"] checks the HTTP request method.

  • $_POST contains submitted form fields.

  • The ?? "" operator supplies an empty string when a field is missing.

  • trim() removes unnecessary whitespace at the beginning and end.

  • htmlspecialchars() safely encodes special characters for HTML output.

Real-World Applications of POST

POST is commonly used for:

  • User registration

  • Login submissions

  • Contact forms

  • Profile updates

  • Product creation

  • Feedback forms

  • Order submissions

Real applications also need appropriate validation, authorization, CSRF protection where relevant, and secure database handling.

5. Difference Between GET and POST in PHP

Feature GET POST
PHP superglobal $_GET $_POST
Data location URL query string HTTP request body
Visible in URL Yes Not normally
Bookmarkable query Usually yes Not in the same way
Common use Search and filters Form submissions and updates
Data size Limited by practical URL constraints Supports larger request bodies, subject to server limits
Automatic encryption No No
Appropriate for passwords No Only with HTTPS and other security measures

Which method should beginners use?

Use GET when the user is requesting or filtering information. Use POST when submitting information that should not be placed in the URL, especially when creating or updating records.

Remember that choosing POST alone does not make a request secure.

6. What Is Form Validation in PHP?

Form validation means checking whether the submitted information meets the application's requirements.

For example, a registration form might require:

  • A name that is not empty

  • A valid email address

  • A password that meets minimum length requirements

  • A selected course

  • A valid mobile number, if required

Validation is important because users can submit incomplete, incorrect, or unexpected information.

HTML validation improves the user experience, but server-side validation in PHP is essential because browser-side checks can be bypassed.

Example: Validate Name and Email

<?php
$errors = [];
$name = "";
$email = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name = trim($_POST["name"] ?? "");
    $email = trim($_POST["email"] ?? "");

    if ($name === "") {
        $errors[] = "Name is required.";
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address.";
    }

    if (empty($errors)) {
        echo "Form validation successful.";
    } else {
        foreach ($errors as $error) {
            echo "<p>" .
                htmlspecialchars($error, ENT_QUOTES, "UTF-8") .
                "</p>";
        }
    }
}
?>

This example demonstrates server-side validation. It assumes the form has already submitted the name and email fields using POST.

Explanation

  • $errors stores validation messages.

  • trim() removes surrounding whitespace.

  • The first condition checks whether the name is empty.

  • filter_var() validates the email format.

  • empty($errors) checks whether any validation errors were recorded.

  • foreach displays each error message.

For a complete application, render the form and the validation response together so users can correct their entries.

7. What Is Sanitization in PHP?

Sanitization refers to transforming input into an appropriate representation for a specific use.

Validation and sanitization are different:

  • Validation checks whether input meets requirements.

  • Sanitization or encoding transforms data to help it meet the needs of a particular context.

For example, a PHP application should validate an email address before accepting it and escape user-provided text when displaying it in HTML.

Example: Safely Display User Input

<?php
$name = $_POST["name"] ?? "";

echo "Welcome, " .
    htmlspecialchars(trim($name), ENT_QUOTES, "UTF-8");
?>

The example removes surrounding whitespace and encodes special HTML characters before output.

This helps prevent user-provided text from being interpreted as HTML markup.

For database operations, use prepared statements instead of relying on HTML escaping or string replacement. Escaping for HTML does not secure SQL queries.

8. Real-World Project: Student Registration Form in PHP

Now let's create a beginner-friendly student registration form that collects a name, email address, and course.

This example validates the submitted fields and displays the accepted information. It does not save records to a database yet.

Create a file named student-registration.php.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Student Registration Form</title>
</head>
<body>

    <h2>Student Registration Form</h2>

    <form method="post" action="">
        <label for="name">Full Name:</label>
        <input
            type="text"
            id="name"
            name="name"
            required
        >

        <br><br>

        <label for="email">Email Address:</label>
        <input
            type="email"
            id="email"
            name="email"
            required
        >

        <br><br>

        <label for="course">Select Course:</label>

        <select id="course" name="course" required>
            <option value="">Choose a course</option>
            <option value="PHP">PHP</option>
            <option value="Web Design">Web Design</option>
            <option value="MySQL">MySQL</option>
        </select>

        <br><br>

        <button type="submit">Register</button>
    </form>

    <?php
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $name = trim($_POST["name"] ?? "");
        $email = trim($_POST["email"] ?? "");
        $course = $_POST["course"] ?? "";

        $allowedCourses = [
            "PHP",
            "Web Design",
            "MySQL"
        ];

        $errors = [];

        if ($name === "") {
            $errors[] = "Please enter your name.";
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = "Please enter a valid email address.";
        }

        if (!in_array($course, $allowedCourses, true)) {
            $errors[] = "Please select a valid course.";
        }

        if (!empty($errors)) {
            foreach ($errors as $error) {
                echo "<p>" .
                    htmlspecialchars($error, ENT_QUOTES, "UTF-8") .
                    "</p>";
            }
        } else {
            echo "<h3>Registration Successful</h3>";

            echo "Name: " .
                htmlspecialchars($name, ENT_QUOTES, "UTF-8") .
                "<br>";

            echo "Email: " .
                htmlspecialchars($email, ENT_QUOTES, "UTF-8") .
                "<br>";

            echo "Course: " .
                htmlspecialchars($course, ENT_QUOTES, "UTF-8");
        }
    }
    ?>

</body>
</html>

How This Project Works

  1. The user enters their name and email address.

  2. The user selects a course.

  3. The browser submits the information using POST.

  4. PHP checks the name and email.

  5. PHP verifies that the selected course belongs to the allowed list.

  6. If validation succeeds, PHP displays the registration details.

  7. If validation fails, PHP displays the relevant error messages.

Real-World Applications

The same basic structure can be extended to build:

  • Student registration systems

  • Employee registration forms

  • Online course applications

  • Customer enquiry forms

  • Event registration systems

  • Membership applications

In a production application, you would also need database storage, duplicate-registration checks, appropriate security controls, and clear handling of successful submissions.

9. How to Run PHP Forms Using XAMPP

If you are a beginner, you can run these examples using XAMPP on your computer.

  1. Install XAMPP.

  2. Start Apache from the XAMPP Control Panel.

  3. Open the htdocs directory in your XAMPP installation.

  4. Create a folder named php-module-8.

  5. Save your PHP files inside that folder.

  6. Open your browser.

  7. Visit http://localhost/php-module-8/student-registration.php.

  8. Fill out the form and click Register.

Make sure the filename and folder match the URL you enter.

PHP files must be processed by a PHP-enabled server. Opening a .php file directly from your computer using a file:// URL will not execute the PHP code.

10. Common Mistakes in PHP Form Handling

Beginners often encounter these problems when processing forms.

Mistake 1: Using the Wrong Superglobal

If a form uses POST but the PHP code reads $_GET, the submitted fields will not be found there.

Solution: Match the PHP superglobal to the form's HTTP method.

Mistake 2: Forgetting the name Attribute

The browser uses field names when submitting form data.

Incorrect:

<input type="text" id="name">

Correct:

<input type="text" id="name" name="name">

Mistake 3: Assuming All Fields Exist

A request can omit fields or submit unexpected values.

Solution: Check that required fields exist and validate their values on the server.

Mistake 4: Trusting HTML Required Attributes

The required attribute provides useful browser-side validation, but it can be bypassed.

Solution: Repeat the necessary validation in PHP.

Mistake 5: Displaying Unescaped Input

Directly inserting user input into HTML can create a cross-site scripting vulnerability.

Solution: Use context-appropriate output encoding, such as htmlspecialchars() for HTML text.

Mistake 6: Storing Passwords as Plain Text

Passwords must never be stored as ordinary text.

Solution: Use PHP's password_hash() to create password hashes and password_verify() to verify passwords. Use HTTPS when transmitting credentials.

Mistake 7: Forgetting CSRF Protection

A sensitive form that changes account or business data may need protection against cross-site request forgery.

Solution: Implement appropriate CSRF tokens and verify them on the server for relevant state-changing requests.

11. Best Practices for PHP Form Handling

Follow these practices when developing real-world PHP applications:

  1. Validate all important form fields on the server.

  2. Use the correct HTTP method for the operation.

  3. Escape untrusted values before displaying them in HTML.

  4. Use prepared statements for database queries.

  5. Use HTTPS to protect information in transit.

  6. Never store passwords in plain text.

  7. Add CSRF protection to relevant state-changing forms.

  8. Validate dropdown selections against server-side allowed values.

  9. Return useful error messages without exposing internal application details.

  10. Keep validation and processing logic organized into reusable functions as your project grows.

These practices help make PHP applications more reliable and secure.

12. Practice Exercises for PHP Form Handling

Try the following exercises to improve your PHP skills.

Exercise 1: Name Form

Create an HTML form that accepts a user's name and displays a personalized welcome message using PHP.

Exercise 2: GET Search Form

Create a search form using GET that accepts a keyword and displays the submitted search term.

Exercise 3: POST Contact Form

Create a contact form containing name, email, and message fields.

Exercise 4: Email Validation

Use filter_var() with FILTER_VALIDATE_EMAIL to validate an email address.

Exercise 5: Required Field Validation

Create a form that checks whether the name and city fields are empty.

Exercise 6: Course Registration

Create a dropdown containing PHP, MySQL, and Web Design. Validate the selected option on the server.

Exercise 7: Number Calculator

Create a form that accepts two numbers and displays their sum after validating the input.

Exercise 8: Student Registration

Create a form that accepts a student's name, email, and course and displays the validated details.

Exercise 9: HTML Output Safety

Submit a string containing HTML special characters and observe how htmlspecialchars() displays it safely as text.

Exercise 10: Database Registration

Extend the student registration form to save the validated details into a MySQL database using PDO or MySQLi prepared statements.

13. Frequently Asked Questions About PHP Form Handling

What is form handling in PHP?

Form handling is the process of receiving, validating, and processing information submitted through an HTML form using PHP.

What is the difference between GET and POST?

GET submits parameters through the URL query string, while POST normally submits fields in the request body. GET is common for searches and filters, while POST is common for submitting or updating information.

What is the $_GET array in PHP?

$_GET is a PHP superglobal array containing query parameters from the current URL.

What is the $_POST array in PHP?

$_POST is a PHP superglobal array containing form fields submitted using the POST method with supported form encoding.

Is POST more secure than GET?

POST does not automatically encrypt data. It avoids putting ordinary form fields into the URL query string, but HTTPS is required to protect data in transit. Sensitive information must also be handled securely on the server.

What is form validation?

Form validation checks whether user input meets the application's rules, such as requiring a name, accepting a valid email address, or selecting an allowed course.

What is the difference between validation and sanitization?

Validation checks whether input meets a requirement. Sanitization transforms data for a particular use. Output encoding is a separate operation used to safely represent untrusted data in a specific context.

Can PHP form data be saved in MySQL?

Yes. PHP can save validated form data in MySQL using PDO or MySQLi prepared statements. A real application should also handle database errors and enforce appropriate security and data-integrity rules.

Why is htmlspecialchars() used in PHP?

htmlspecialchars() converts certain special characters into HTML entities. It is useful for displaying untrusted text in HTML without allowing those characters to be interpreted as markup.

Can I run a PHP form without XAMPP?

Yes. You can use another PHP-enabled web server or PHP's built-in development server. XAMPP is simply one popular beginner-friendly option.

Conclusion

Form handling is one of the most important skills in Core PHP programming. It allows websites to collect information from users and process it on the server.

In this module, we learned HTML forms, the GET and POST methods, form validation, safe output handling, and a practical student registration project.

We also discussed common mistakes, security considerations, and best practices for real-world applications.

Practice each example and make sure you understand how the browser submits data and how PHP processes it. Once you are comfortable with these concepts, you will be ready to connect forms to a MySQL database and build more complete web applications.