0
0
PHPprogramming~5 mins

Input validation and sanitization in PHP

Choose your learning style9 modes available
Introduction

Input validation and sanitization help keep your program safe and working well by checking and cleaning user data.

When a user submits a form with their name and email.
When accepting a number from a user for calculations.
When saving user comments to a website.
When processing file uploads from users.
When receiving data from an API or external source.
Syntax
PHP
<?php
// Validate input
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Input is a valid email
}

// Sanitize input
$clean_name = strip_tags($name);
?>

Use filter_var() to check or clean data.

Validation checks if data is correct; sanitization cleans unwanted parts.

Examples
This checks if the email is valid and prints a message.
PHP
<?php
$email = "user@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email.";
} else {
    echo "Invalid email.";
}
?>
This removes HTML tags from the name to keep it safe.
PHP
<?php
$name = "John <b>Doe</b>";
$clean_name = strip_tags($name);
echo $clean_name;
?>
This keeps only numbers from the age input.
PHP
<?php
$age = "25 years";
$clean_age = filter_var($age, FILTER_SANITIZE_NUMBER_INT);
echo $clean_age;
?>
Sample Program

This program checks if the email is valid and cleans the name to remove harmful code.

PHP
<?php
// Sample program to validate and sanitize user input
$user_email = "test@example.com";
$user_name = "Alice <script>alert('x');</script>";

// Validate email
if (filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
    echo "Email is valid.\n";
} else {
    echo "Email is invalid.\n";
}

// Sanitize name
$safe_name = strip_tags($user_name);
echo "Sanitized name: " . $safe_name . "\n";
?>
OutputSuccess
Important Notes

Always validate before sanitizing to catch bad data early.

Sanitization helps prevent security problems like code injection.

Use the right filter for the type of data you expect.

Summary

Input validation checks if data is correct and safe.

Sanitization cleans data by removing unwanted parts.

Use PHP's filter_var() function for both tasks.