Skip to content

PHP Tutorial Forms and User Input

Sanitizing Input

Lesson 140 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Three words are often mixed up. They are different steps with different jobs.

StepQuestion it answersWhen
ValidateIs this acceptable? Yes or noWhen data comes in
SanitizeCan I clean it up safely?When data comes in
EscapeCan I print or store it safely here?When data goes out

Validate

Reject anything that does not fit the rule. This is the strongest protection, and you already used it in Form Validation.

Sanitize: gentle cleaning

Sanitizing changes harmless parts of the value. The most common cleaning is trim().

index.php
PHP
<?php
$input = "   isha@example.com \n";

echo "[" . trim($input) . "]";
Output
OUTPUT
[isha@example.com]

You can also normalise values, for example lowercasing an email or removing everything except digits from a phone number.

index.php
PHP
<?php
$email = strtolower(trim("  Isha@Example.COM "));
$phone = preg_replace('/\D+/', '', "+91 98765-43210");

echo $email . "\n" . $phone;
Output
OUTPUT
isha@example.com
919876543210

filter_var sanitize filters

PHP has filters such as FILTER_SANITIZE_NUMBER_INT, but be careful: they remove characters silently and can hide a wrong value. It is usually better to validate and show an error.

Escape: depends on where it goes

Escaping depends on where the value will be used. There is no single “make it safe” function.

Where the value goesUse
HTML pagehtmlspecialchars()
SQL queryPrepared statements (never string joining)
A URL parameterurlencode() or http_build_query()
A shell commandescapeshellarg() (better: avoid shell commands)
JSONjson_encode()
index.php
PHP
<?php
$name = 'Isha <script>alert("x")</script>';

echo htmlspecialchars($name, ENT_QUOTES, "UTF-8");
Output
OUTPUT
Isha &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;

Do not store HTML-escaped text

Save the original value in the database, and escape when you print it. If you escape before saving, the text looks broken everywhere else (in an email, in JSON, in a PDF).

Old functions to avoid

  • FILTER_SANITIZE_STRING was deprecated in PHP 8.1. Do not use it.
  • addslashes() and mysql_real_escape_string() are not the right protection for SQL. Use prepared statements.
  • strip_tags() does not make text safe for every context.
  • magic_quotes was removed long ago.

A simple intake helper

index.php
PHP
<?php
function cleanText(mixed $value): string
{
    return is_string($value) ? trim($value) : "";
}

echo "[" . cleanText("  hello ") . "]\n";
echo "[" . cleanText(["x"]) . "]";
Output
OUTPUT
[hello]
[]
dangerous
Escape at the last moment
Escape when you output, for the place you output to. HTML escaping protects HTML only, so it does not protect an SQL query. The security chapter covers each context.