SyntaxStudy
Sign Up
php

How to Validate a Form in PHP

Sanitize and validate form input in PHP to prevent XSS and SQL injection.

Always validate and sanitize user input on the server side — never trust data from the browser.

Sanitization vs Validation

  • Sanitize — clean input to remove harmful characters
  • Validate — check that input meets requirements (required, correct type, etc.)

Functions

  • htmlspecialchars() — escape HTML special characters (prevents XSS)
  • filter_var() — validate and sanitize various data types
  • trim() — remove whitespace
  • strip_tags() — remove HTML and PHP tags

Never

Never insert raw user input into SQL queries — use prepared statements.

Example
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $errors = [];

    // Sanitize
    $name  = trim(htmlspecialchars($_POST['name'] ?? ''));
    $email = trim($_POST['email'] ?? '');
    $age   = intval($_POST['age'] ?? 0);

    // Validate
    if (empty($name)) {
        $errors[] = 'Name is required.';
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Invalid email address.';
    }

    if ($age < 18 || $age > 120) {
        $errors[] = 'Age must be between 18 and 120.';
    }

    if (empty($errors)) {
        // Process form...
        echo 'Form submitted successfully!';
    }
}