Three words are often mixed up. They are different steps with different jobs.
| Step | Question it answers | When |
|---|---|---|
| Validate | Is this acceptable? Yes or no | When data comes in |
| Sanitize | Can I clean it up safely? | When data comes in |
| Escape | Can 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().
<?php
$input = " isha@example.com \n";
echo "[" . trim($input) . "]";
[isha@example.com]
You can also normalise values, for example lowercasing an email or removing everything except digits from a phone number.
<?php
$email = strtolower(trim(" Isha@Example.COM "));
$phone = preg_replace('/\D+/', '', "+91 98765-43210");
echo $email . "\n" . $phone;
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 goes | Use |
|---|---|
| HTML page | htmlspecialchars() |
| SQL query | Prepared statements (never string joining) |
| A URL parameter | urlencode() or http_build_query() |
| A shell command | escapeshellarg() (better: avoid shell commands) |
| JSON | json_encode() |
<?php
$name = 'Isha <script>alert("x")</script>';
echo htmlspecialchars($name, ENT_QUOTES, "UTF-8");
Isha <script>alert("x")</script>
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_STRINGwas deprecated in PHP 8.1. Do not use it.addslashes()andmysql_real_escape_string()are not the right protection for SQL. Use prepared statements.strip_tags()does not make text safe for every context.magic_quoteswas removed long ago.
A simple intake helper
<?php
function cleanText(mixed $value): string
{
return is_string($value) ? trim($value) : "";
}
echo "[" . cleanText(" hello ") . "]\n";
echo "[" . cleanText(["x"]) . "]";
[hello]
[]