0Pricing
PHP Academy · Lesson

Form Validation

Validate user inputs for security and correctness.

Form Validation is a free PHP Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Validating and Securing Form Inputs

Welcome to the next lesson! In this lesson, you’ll learn how to validate and secure user inputs to ensure your forms are accurate and protected from malicious attacks. Let’s dive in!

Form Validation — illustration 1

2

Why Validate and Secure Inputs?

Validating and securing form inputs is crucial to:

  • Ensure data accuracy and usability.
  • Protect against security threats like SQL injection and XSS attacks.

Key Point: Always validate and sanitize user inputs before processing or storing them.

3

Validating Inputs

Use PHP’s built-in functions to validate common inputs:

  • filter_var(): Validates email, URLs, and integers.
  • preg_match(): Validates inputs against regular expressions.

Example: Validating an email address:

<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST["email"];
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo "Valid email: $email";
    } else {
      echo "Invalid email address.";
    }
  }
?>

4

Sanitizing Inputs

Sanitize inputs to remove unwanted characters or harmful code. Example:

Tip: Use filter_var() with appropriate filters for different types of data.

<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
    echo "Sanitized Name: $name";
  }
?>

5

Preventing Cross-Site Scripting (XSS)

Escape special characters to prevent XSS attacks. Use:

  • htmlspecialchars(): Converts special characters to HTML entities.

Example:

Tip: Always escape user inputs before displaying them in the browser.

<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $comment = htmlspecialchars($_POST["comment"]);
    echo "Comment: $comment";
  }
?>

6

Preventing SQL Injection

SQL injection occurs when malicious code is inserted into your SQL queries. Use prepared statements to prevent it. Example:

Key Point: Always use prepared statements for database interactions.

<?php
  $pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
  $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
  $stmt->execute(["username" => $_POST["username"]]);
  $user = $stmt->fetch();
?>

7

Common Validation Patterns

Here are some common patterns:

  • Validating a phone number: preg_match('/^\d{10}$/', $phone)
  • Validating a password: Check length and complexity.

Example: Validating a strong password:

<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $password = $_POST["password"];
    if (strlen($password) >= 8 && preg_match('/[A-Z]/', $password)) {
      echo "Strong password!";
    } else {
      echo "Password must be at least 8 characters long and include an uppercase letter.";
    }
  }
?>

8

Securing File Uploads

For forms handling file uploads:

  • Check the file type and size.
  • Store files in a secure directory outside the web root.

Example:

<?php
  if ($_FILES["file"]["size"] < 500000 && in_array($_FILES["file"]["type"], ["image/jpeg", "image/png"])) {
    move_uploaded_file($_FILES["file"]["tmp_name"], "/secure/location/" . $_FILES["file"]["name"]);
    echo "File uploaded successfully!";
  } else {
    echo "Invalid file.";
  }
?>

9

10

Great Job!

Congratulations! You’ve learned how to validate and secure form inputs to ensure your web applications are safe and reliable. In the next lesson, we’ll explore handling file uploads in PHP. Let’s keep coding!

Form Validation — illustration 10

Frequently asked questions

Is the “Form Validation” lesson free?

Yes — the full text of “Form Validation” is free to read here on the web, and the PHP Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Form Validation”?

Validate user inputs for security and correctness. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Form Validation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Creating HTML Forms
  2. Handling Form Data with PHP
  3. Form Validation
← Back to PHP Academy