Form Processing & XSS Protection
Processing HTML forms is a core task in PHP. To prevent security vulnerabilities like Cross-Site Scripting (XSS), you must sanitize all user inputs before displaying them.
1 XSS Attacks and htmlspecialchars() Sanitization
If you output raw user input directly to an HTML page, attackers can inject malicious JavaScript code (a Cross-Site Scripting or XSS attack). To prevent this, always pass user inputs to **`htmlspecialchars()`**, which encodes characters like `<` and `>` into safe HTML entities (`<` and `>`), rendering the script harmlessly as text.
2 Sanitization Code
Let's run a program demonstrating sanitization checks:
PHP — Sanitization
▶ Run Code
<?php
// Malicious script payload input by user
$userInput = "<script>alert('Hacked!');</script>";
// Vulnerable output (executes script)
// echo "Unsafe: " . $userInput . "\n";
// Secure output (renders harmlessly as plain text)
$safeOutput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo "Safe: " . $safeOutput . "\n";
?>
3 Code Challenge
Challenge: Write a script validating if an input string is a valid email using `filter_var()` with the `FILTER_VALIDATE_EMAIL` constant. Print whether the check passed or failed.