Sanitizing User Input
Remove dangerous characters with htmlspecialchars and filter_input.
Sanitizing User Input is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Sanitization vs Validation
Validation checks if data meets requirements (and rejects it if not).
Sanitization cleans data by removing or encoding dangerous characters so it's safe to use.
Both are needed — validate first, then sanitize for output.
htmlspecialchars() for HTML Output
Always escape output before inserting into HTML to prevent XSS:
<?php
$name = '<script>alert(1)</script>';
// Dangerous — executes script:
// echo $name;
// Safe:
echo htmlspecialchars($name, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// <script>alert(1)</script>htmlentities() vs htmlspecialchars()
Both escape HTML, but htmlentities converts ALL applicable characters; htmlspecialchars only converts the five most dangerous ones:
<?php
$str = '<b>café</b> & "bar"';
// htmlspecialchars: only & < > ' "
echo htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
// htmlentities: also converts é → é
echo htmlentities($str, ENT_QUOTES, 'UTF-8');
// Prefer htmlspecialchars — htmlentities can break UTF-8filter_var FILTER_SANITIZE_*
filter_var sanitize modes strip dangerous content:
<?php
$rawEmail = 'user(bad)@exam<ple.com';
$clean = filter_var($rawEmail, FILTER_SANITIZE_EMAIL);
echo $clean; // user@example.com
$rawUrl = 'http://exa mple.com/pa th?q=foo bar';
$cleanUrl = filter_var($rawUrl, FILTER_SANITIZE_URL);
echo $cleanUrl;strip_tags()
Remove HTML tags from a string, optionally keeping allowed tags:
<?php
$input = '<p>Hello <b>World</b> <script>alert(1)</script></p>';
// Remove all tags:
echo strip_tags($input);
// Hello World alert(1)
// Keep only <b> and <i>:
echo strip_tags($input, '<b><i>');
// Hello <b>World</b>Sanitizing for SQL
Never sanitize SQL with string functions — always use prepared statements. The correct approach:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
// WRONG — even with addslashes this is dangerous:
// $sql = "SELECT * FROM users WHERE email = '" . addslashes($email) . "'";
// CORRECT — prepared statement:
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute([':email' => $email]);
$user = $stmt->fetch();addslashes() vs Prepared Statements
addslashes() escapes backslashes and quotes — but it's NOT safe for SQL. Use PDO prepared statements instead. addslashes() may still be useful for non-SQL purposes like JavaScript string generation:
<?php
// For embedding PHP string into JavaScript (still escape via json_encode):
$jsData = json_encode(['name' => $userInput], JSON_HEX_QUOT);
echo "<script>var data = $jsData;</script>";Sanitizing File Names
Strip dangerous characters from uploaded file names:
<?php
function sanitizeFilename(string $name): string {
// Remove path traversal chars and other dangerous ones
$name = basename($name); // strip any path
$name = preg_replace('/[^a-zA-Z0-9._-]/', '_', $name); // only safe chars
$name = preg_replace('/_{2,}/', '_', $name); // collapse underscores
return strtolower($name);
}
echo sanitizeFilename('../../../etc/passwd'); // etc_passwd
echo sanitizeFilename('My Photo (1).JPG'); // my_photo_1_.jpgInteger Casting for IDs
The simplest sanitization for numeric IDs — cast to int, which discards any non-numeric content:
<?php
// Never do this:
$id = $_GET['id'];
$sql = "SELECT * FROM posts WHERE id = $id";
// Safe approach 1: cast to int
$id = (int) ($_GET['id'] ?? 0);
if ($id <= 0) die('Invalid ID');
// Safe approach 2: validate
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) die('Invalid ID');Output Context Matters
Different output contexts need different escaping:
- HTML body →
htmlspecialchars() - HTML attribute →
htmlspecialchars(ENT_QUOTES) - JSON/JavaScript →
json_encode() - URL parameter →
urlencode() - SQL → prepared statements
urlencode and rawurlencode
Encode values for use in URLs:
<?php
$search = 'hello world & PHP';
echo urlencode($search);
// hello+world+%26+PHP (+ for spaces)
echo rawurlencode($search);
// hello%20world%20%26%20PHP (RFC 3986 — use in paths)
$url = 'https://example.com/search?q=' . urlencode($search);
echo $url;Quick Check
Which function is the correct way to prevent SQL injection when using user input in a database query?
Recap: Sanitizing Input
Sanitization rules:
- HTML output →
htmlspecialchars(ENT_QUOTES, 'UTF-8') - SQL → prepared statements, never string escaping
- URLs →
urlencode()orrawurlencode() - File names → strip with regex, use
basename() - Integer IDs → cast with
(int) - Tags →
strip_tags()for allowed-tag filtering
Frequently asked questions
Is the “Sanitizing User Input” lesson free?
Yes — the full text of “Sanitizing User Input” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Sanitizing User Input”?
Remove dangerous characters with htmlspecialchars and filter_input. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Sanitizing User Input” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.