You are currently viewing PHP 8 Free Course – Lesson 8: Working with Forms and Data
PHP 8 Free Course

PHP 8 Free Course – Lesson 8: Working with Forms and Data

1. Introduction

Welcome to Lesson 8 of the PHP 8 Free Course! In this lesson, we delve deeper into an essential aspect of web development—working with forms and data. Mastering the art of handling form data efficiently and securely is a cornerstone for building interactive and dynamic web applications. Forms serve as the bridge between the user and the server, enabling the seamless flow of data. They are instrumental in gathering input from users, which could range from simple text inputs to file uploads.

The data collected via forms can serve various purposes, such as user registration, login authentication, data filtering, and much more. However, working with forms also poses certain security risks. A lack of proper validation and sanitization could leave your application vulnerable to malicious attacks. Therefore, understanding how to process form data securely is crucial.

In this lesson, we will start by understanding the basic HTTP methods involved in form submission, namely GET and POST. Following this, we will delve into creating simple forms, processing form data, validating and sanitizing user input to ensure it’s safe and adheres to the expected format, and finally, implementing measures to secure form submissions against Cross-Site Request Forgery (CSRF) attacks.

As you progress through this lesson, you’ll acquire the knowledge and skills necessary to create forms, process user inputs securely, and build more interactive and user-friendly web applications. Before diving into the lesson, if you need a refresher on any of the previous topics, feel free to navigate through the PHP 8 Free Course index.

Whether you are developing a simple contact form, a complex multi-step registration form, or anything in between, the principles covered in this lesson will provide a solid foundation to ensure your forms are both functional and secure.

2. Understanding HTTP Methods

Forms can be submitted using two primary HTTP methods: GET and POST.

  • GET: Suitable for fetching data; form data is appended to the URL.
  • POST: Suitable for submitting sensitive or large amounts of data; form data is included in the body of the request.

3. Creating Forms

Creating a form in HTML that submits data to a PHP script is straightforward.

<form action="process.php" method="post">
    Name: <input type="text" name="name"><br>
    Email: <input type="text" name="email"><br>
    <input type="submit" value="Submit">

4. Processing Form Data

Once the form is submitted, the data can be accessed in PHP using the $_POST or $_GET superglobals, depending on the method used.

$name = $_POST['name'];
$email = $_POST['email'];

5. Validating Form Data

Validation ensures the data submitted is correct and safe to be used. Here are some validation examples:

if (empty($_POST["name"])) {
    $nameErr = "Name is required";
} else {
    $name = test_input($_POST["name"]);

if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $email = $_POST['email'];
} else {
    $emailErr = "Invalid email format";

// Additional validation examples are provided later in this lesson.

6. Sanitizing Form Data

Sanitizing ensures the data is clean and free from any malicious code.

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

7. Cross-Site Request Forgery (CSRF) Protection

CSRF attacks primarily target state-changing requests, not data theft, as attackers trick the user into submitting a request to a web app on which they’re authenticated. To mitigate this, it’s essential to implement anti-CSRF tokens in your forms. Here’s a more detailed approach to implementing CSRF protection in PHP:

1. Generating CSRF Tokens:
  • Random Token Generation: Generate a random token each time the form is created. Store this token in the user’s session and also include it within the form as a hidden field.
$token = bin2hex(random_bytes(32));
$_SESSION['token'] = $token;
<form action="process.php" method="post">
    <!-- other form fields -->
    <input type="hidden" name="token" value="<?php echo $token; ?>">
    <input type="submit" value="Submit">
2. Verifying CSRF Tokens:
  • Token Verification: When the form is submitted, compare the token from the form with the token stored in the user’s session.
if ($_POST['token'] !== $_SESSION['token']) {
    die('Invalid CSRF token.');
3. Token Expiry:
  • Expiry Time: You can also implement an expiry time for tokens to increase security.
$_SESSION['token_time'] = time();
// Verifying token time
if (time() - $_SESSION['token_time'] > 300) {  // Token expires after 300 seconds
    die('CSRF token expired.');
4. Double Submit Cookies:
  • Double Submit: Another method is to submit the token in both a cookie and a form field, and then verify on the server that they match.
setcookie('csrf_token', $token, 0, '/', '', false, true);  // Create a cookie
// Verification
if ($_POST['token'] !== $_COOKIE['csrf_token']) {
    die('Invalid CSRF token.');

5. External Libraries:

  • PHP Libraries: Libraries such as PHP-CSRF-Protector can be used to automate CSRF protection in your applications.
  • PHP-CSRF-Protector on GitHub
6. Other Precautions:
  • Same-Site Cookies: Utilize Same-Site cookies to ensure that cookies are only sent with requests originating from the same domain.
  • Content Security Policy (CSP): Implement Content Security Policy headers to reduce the risk of CSRF attacks.

7. Further Reading and Resources

  1. OWASP: Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet
  2. PHP-CSRF-Protector on GitHub
  3. MDN Web Docs: SameSite cookies explained

8. Exercises

  1. Form Creation and Processing:
  • Create a form with various input types and write a PHP script to process the submitted data.
  1. Data Validation and Sanitization:
  • Extend the script to include validation and sanitization of the form data.
  1. Secure Form Submission:
  • Implement CSRF protection for your form.

9. Further Reading and Resources

  1. PHP: Dealing with Forms – Manual
  2. PHP: Data Filtering – Manual
  3. OWASP: Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet

Proceed with Lesson 9: Interacting with the Database to learn how to work with databases in PHP. For a broader range of programming topics, explore the programming section on our blog.

Leave a Reply