Lecture Notes of Class 11 Forms and User Input in PHP

Rashmi Mishra
0

Lecture Notes of Class 11

Forms and User Input in PHP

Objective

  • To understand how to collect, validate, and process user input from HTML forms using PHP.
  • Learn basic form validation and sanitization techniques to ensure secure handling of user data.

Outcome

  • By the end of this lesson, students will be able to:
    • Create HTML forms to collect data from users.
    • Process user input data using PHP's $_GET and $_POST superglobals.
    • Implement validation and sanitization techniques to secure form data.

1. Understanding HTML Forms

HTML forms allow you to collect user input on web pages. For example, forms are used for collecting login information, feedback, or survey responses. Forms can include various types of fields, such as:

  • Text fields: for single-line text input.
  • Password fields: for hidden text (e.g., passwords).
  • Email fields: to collect email addresses.
  • Submit buttons: to send the form data.

Basic HTML Form Structure

An HTML form typically includes a form tag (<form>) with input fields inside it. The action attribute defines the page where the data is sent after submission, and the method attribute determines how the data is transmitted.

Example: Simple HTML Form

    <form action="process_form.php" method="post">

      <label for="username">Username:</label>

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

      <label for="email">Email:</label>

      <input type="email" id="email" name="email" required>

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

    </form>

  • action: Specifies the URL where the form data will be processed. In this example, it sends data to process_form.php.
  • method: Defines the HTTP method for data submission (POST in this case). The alternative method, GET, sends data as URL parameters.

2. GET vs POST Methods in Form Submission

PHP uses $_GET and $_POST superglobal arrays to retrieve data sent by forms.

Using GET

  • The GET method appends form data to the URL (e.g., process_form.php?username=value&email=value).
  • Suitable for non-sensitive data, like search queries.
  • Data is accessible through the $_GET array in PHP.

Using POST

  • The POST method hides data within the HTTP request body.
  • Ideal for sensitive data like passwords since it doesn’t appear in the URL.
  • Accessed in PHP using the $_POST array.
SUPER GLOBAL VARIABLE(In Detail)---->Click Here

3. Accessing Form Data in PHP

When a user submits the form, PHP can retrieve the data by using $_GET or $_POST arrays, depending on the method used.

Example: 

Accessing Data with POST

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        // Collect form data

        $username = $_POST['username'];

        $email = $_POST['email'];   

        // Display the data

        echo "Username: $username<br>";

        echo "Email: $email<br>";

    }

     

     

  • Explanation: $_SERVER["REQUEST_METHOD"] checks if the request method is POST.
  • Output: If a user submits a form with username and email, this script will display the data back on the page.

4. Form Validation

Validation checks if the submitted data meets specific requirements before processing it. This can prevent errors and malicious inputs.

Types of Form Validation

  1. Required Fields: Ensures essential fields are not left empty.
  2. Email Validation: Verifies the correct email format.
  3. Numeric Validation: Ensures only numbers are entered.
  4. String Length Validation: Limits the number of characters a user can input.

PHP Validation Techniques

PHP provides functions to validate different types of data.

Example: 

Required Field and Email Validation

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        // Initialize variables

        $errors = []; // Array to hold error messages   

        // Check username

        if (empty($_POST["username"])) {

            $errors[] = "Username is required.";

        } else {

            $username = $_POST["username"];

        }

       

        // Check email

        if (empty($_POST["email"])) {

            $errors[] = "Email is required.";

        } else {

            $email = $_POST["email"];

            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

                $errors[] = "Invalid email format.";

            }

        }

       

        // Display Errors

        if (!empty($errors)) {

            foreach ($errors as $error) {

                echo $error . "<br>";

            }

        } else {

            echo "Form submitted successfully!<br>";

            echo "Username: $username<br>";

            echo "Email: $email<br>";

        }

    }

     

     

  • Explanation: empty() checks if the field is left blank. If so, an error message is added to $errors. filter_var() with FILTER_VALIDATE_EMAIL checks if an email format is correct.
  • Output: Displays an error message if any field is invalid or blank.

5. Data Sanitization

Sanitization cleans input data to prevent harmful code from being injected. This is essential to protect against XSS (Cross-Site Scripting) attacks and other vulnerabilities.

PHP Sanitization Techniques

  1. htmlspecialchars(): Converts special characters to HTML entities to prevent HTML injection.
  2. filter_var(): Has built-in filters to sanitize different types of input, like emails or URLs.

Example: 

Sanitizing Input Data

    $username = htmlspecialchars($_POST["username"]);

    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);

     

  • Explanation:
    • htmlspecialchars() encodes special characters, so any <script> tags entered will not run as code.
    • FILTER_SANITIZE_EMAIL removes invalid characters from an email address.

6. Complete Example: 

Form with Validation and Sanitization

Below is a complete example demonstrating form validation and sanitization in action.

HTML Form (form.html)

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Form Validation Example</title>

</head>

<body>

    <form action="process_form.php" method="post">

        <label for="username">Username:</label>

        <input type="text" id="username" name="username" required><br>

 

        <label for="email">Email:</label>

        <input type="email" id="email" name="email" required><br>

 

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

    </form>

</body>

</html>

 

 PHP Script to Process Data (process_form.php)


if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Initialize variables

    $username = $email = "";

    $errors = []; // Array to store error messages

 

    // Validate and Sanitize Username

    if (empty($_POST["username"])) {

        $errors[] = "Username is required.";

    } else {

        $username = htmlspecialchars($_POST["username"]);

    }

 

    // Validate and Sanitize Email

    if (empty($_POST["email"])) {

        $errors[] = "Email is required.";

    } else {

        $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

            $errors[] = "Invalid email format.";

        }

    }

 

    // Check for Errors or Display Success

    if (!empty($errors)) {

        foreach ($errors as $error) {

            echo $error . "<br>";

        }

    } else {

        echo "Form submitted successfully!<br>";

        echo "Username: $username<br>";

        echo "Email: $email<br>";

    }

}

 

 


7. Summary

  • Forms are used to collect data from users on web pages.
  • PHP provides $_GET and $_POST superglobals to retrieve form data.
  • Validation ensures data is complete and in the correct format, using functions like empty() and filter_var().
  • Sanitization cleans input data to prevent malicious code, using functions like htmlspecialchars().

8. Practice Exercises

  1. Create a Login Form: Create a form with fields for username and password. Validate that both fields are filled in before displaying a success message.
  2. Contact Form: Build a form with fields for name, email, and message. Ensure that the email is valid and all fields are sanitized before displaying the message back to the user.


Post a Comment

0Comments

Post a Comment (0)