PHP Form Sanitization
Sanitizing input means cleaning up user-submitted data to remove unwanted or potentially dangerous characters before storing or displaying it. This helps protect your application from attacks like Cross-Site Scripting (XSS).
PHP's filter_var() function, combined with sanitization filters, and functions like htmlspecialchars() and trim(), are commonly used together to sanitize form input safely.
trim($str);
htmlspecialchars($str);Sanitizing strings
trim() removes extra whitespace, and htmlspecialchars() converts special characters like < and > into safe HTML entities, preventing malicious scripts from executing when the data is displayed.
Using filter_var for sanitization
filter_var($value, FILTER_SANITIZE_FULL_SPECIAL_CHARS) is a built-in way to remove or encode unwanted characters from user input.
<?php
$input = " Hello World ";
echo trim($input);
?>Hello Worldtrim() removes the leading and trailing whitespace from the string.
<?php
$comment = "<script>alert(1)</script>";
echo htmlspecialchars($comment);
?><script>alert(1)</script>htmlspecialchars() converts dangerous HTML characters into safe entities before display.
Key points
- Sanitization removes or encodes potentially dangerous input.
- trim() removes unwanted leading and trailing whitespace.
- htmlspecialchars() prevents XSS by escaping special HTML characters.
- Always sanitize data before displaying it back to users.
