PHP ยท Chapter 26 of 44

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.

Syntax
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.

Example 1 (php)
<?php
  $input = "  Hello World  ";
  echo trim($input);
?>
Output
Hello World

trim() removes the leading and trailing whitespace from the string.

Example 2 (php)
<?php
  $comment = "<script>alert(1)</script>";
  echo htmlspecialchars($comment);
?>
Output
&lt;script&gt;alert(1)&lt;/script&gt;

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.
๐Ÿ’ก Note: Sanitize on output (when displaying) and validate on input to keep your application both correct and secure.

๐Ÿ“ Quick Quiz

1. What does htmlspecialchars() protect against?

2. What does trim() remove?

3. When should sanitization happen?