PHP Form Validation

PHP Form Validation Tutorial (Complete Guide with Examples)

Welcome to phponline.in, your complete guide to mastering PHP programming.

In this tutorial, you will learn PHP Form Validation in detail:

  • Why validation is important
  • Client-side vs server-side validation
  • Required field validation in PHP
  • Email, phone number, and password validation
  • Input sanitization methods
  • Validation using filter_var() and Regular Expressions (Regex)
  • Real-world projects: login form, registration form, contact form validation
  • Security best practices in form validation

👉 Related: PHP Form Handling


You Will Learn

  1. Introduction to PHP Form Validation
  2. Importance of Form Validation
  3. Client-Side vs Server-Side Validation
  4. PHP Superglobals for Validation
  5. Basic Required Field Validation
  6. Email Validation in PHP
  7. Password Validation in PHP
  8. Username Validation (Letters and Numbers Only)
  9. Phone Number Validation in PHP
  10. Age and Number Validation
  11. URL Validation
  12. Date Validation
  13. File Upload Validation
  14. Radio Button Validation
  15. Checkbox Validation
  16. Dropdown (Select) Validation
  17. Textarea Validation
  18. Password Strength Check (Regex Example)
  19. Matching Passwords Validation (Confirm Password)
  20. Multiple Field Validation Example
  21. Sticky Forms (Retaining Input After Errors)
  22. Using filter_var() for Validation
  23. Validation with Regex in PHP
  24. Sanitizing Input with htmlspecialchars()
  25. Sanitizing with trim(), stripslashes(), strip_tags()
  26. Preventing XSS with Form Validation
  27. Preventing SQL Injection with Validation + Prepared Statements
  28. PHP Error Messages for Invalid Inputs
  29. Displaying Validation Errors Near Form Fields
  30. PHP Validation Functions (Reusable Code)
  31. Contact Form Validation Example
  32. Registration Form Validation Example
  33. Login Form Validation Example
  34. Feedback Form Validation Example
  35. Secure Form Validation Workflow
  36. Validation and Database Insertion (MySQL Example)
  37. Real-World Example: Newsletter Signup Form Validation
  38. Real-World Example: Survey Form Validation
  39. Secure File Upload Form Validation
  40. Multi-Step Form Validation
  41. Using Sessions in Form Validation
  42. Using Cookies with Validation (Optional)
  43. PHP Form Validation Best Practices
  44. Common Mistakes in Validation
  45. Validation Checklist for Secure Forms
  46. Mini Project 1: Validated Registration Form with MySQL
  47. Mini Project 2: Validated Contact Form with Email Sending
  48. Mini Project 3: Validated Login System with Sessions
  49. PHP Form Validation Security Tips

1. Introduction to PHP Form Validation

Form validation in PHP ensures that the data entered by users is correct, complete, and safe before storing or using it.

Without validation, users might:

  • Leave fields blank
  • Enter invalid data (e.g., text instead of numbers)
  • Insert malicious code (XSS or SQL Injection)

👉 Example: A user enters “abc” in an age field. Validation ensures only a number is accepted.


5. Basic Required Field Validation

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    echo "Name is required";
  } else {
    $name = htmlspecialchars($_POST["name"]);
    echo "Welcome, $name";
  }
}

👉 Related: PHP Variables


6. Email Validation in PHP

$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo "Invalid email format";
} else {
  echo "Valid email";
}

7. Password Validation in PHP (Minimum Length)

$password = $_POST["password"];
if (strlen($password) < 6) {
  echo "Password must be at least 6 characters long";
}

👉 Related: PHP Strings


10. Age and Number Validation

$age = $_POST["age"];
if (!filter_var($age, FILTER_VALIDATE_INT)) {
  echo "Invalid age. Please enter a number.";
}

18. Password Strength Check (Regex Example)

$password = $_POST["password"];
if (!preg_match("/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$/", $password)) {
  echo "Password must contain at least 8 characters, one uppercase, one lowercase, and one digit.";
}

23. Validation with Regex in PHP

  • Email Regex: /^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i
  • Phone Regex: /^[0-9]{10}$/
  • Username Regex: /^[A-Za-z0-9_]{3,20}$/

31. Contact Form Validation Example

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

  if (empty($name) || empty($email) || empty($message)) {
    echo "All fields are required";
  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
  } else {
    echo "Thank you, $name. We received your message.";
  }
}

👉 Related: PHP Form Handling


32. Registration Form Validation Example

  • Validate Name (letters only)
  • Validate Email
  • Validate Password (min length, confirm password)
  • Store securely in MySQL database with prepared statements

36. Validation + Database Insertion

$conn = mysqli_connect("localhost", "root", "", "testdb");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = mysqli_real_escape_string($conn, $_POST["name"]);
  $email = mysqli_real_escape_string($conn, $_POST["email"]);

  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email";
  } else {
    $sql = "INSERT INTO users (name, email) VALUES (?, ?)";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "ss", $name, $email);
    mysqli_stmt_execute($stmt);
    echo "Registration successful";
  }
}

👉 Related: [PHP MySQL Integration]


43. PHP Form Validation Best Practices

  • Always validate on the server-side (not only JavaScript).
  • Use filter_var() for built-in validation.
  • Sanitize input before displaying.
  • Use prepared statements for DB queries.
  • Display clear error messages near fields.

Mini Project: Validated Registration Form with MySQL

Includes:

  • Name, Email, Password, Confirm Password fields
  • Validation for required fields, email format, password strength
  • Data stored in MySQL database securely

Summary & Conclusion

  • PHP Form Validation ensures security and correctness of data.
  • Always validate + sanitize user input.
  • Use built-in methods like filter_var() when possible.
  • Prevent XSS and SQL Injection with proper validation.

👉 Next, check: PHP Regular Expressions


FAQs on PHP Form Validation

Q1: Why is form validation important in PHP?
A: To ensure users enter valid, secure, and complete data.

Q2: What’s the difference between client-side and server-side validation?
A: Client-side uses JavaScript (quick but insecure), server-side uses PHP (secure).

Q3: How to validate email in PHP?
A: Use filter_var($email, FILTER_VALIDATE_EMAIL).

Q4: How to validate passwords in PHP?
A: Check length, complexity, and use regex for strong password rules.

Q5: How to prevent SQL Injection in forms?
A: Always use prepared statements with parameter binding.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments