Skip to content

How can I sanitize user input with PHP?

There are several ways to handle user input in PHP, depending on the type of data and how you plan to use it. Here are some common methods:

  1. Use htmlspecialchars() to encode special characters when outputting data to HTML. This is useful for preventing script injection (XSS) attacks by converting characters like < and > into HTML entities.
  2. Use strip_tags() to remove HTML and PHP tags from a string. This is useful when you want to allow users to format their input with basic HTML tags, but want to remove potentially malicious tags.
  3. Use trim() to remove leading and trailing whitespace from a string. This is useful for cleaning up user input formatting, though it does not address security concerns.
  4. Avoid addslashes() for database queries, as it is obsolete and unsafe for preventing SQL injection. Instead, use prepared statements with PDO or MySQLi to safely handle user input in SQL queries.
  5. Use filter_var() with a specific filter flag to sanitize user input. For example, you can use FILTER_SANITIZE_EMAIL to remove all illegal characters from an email address.
php
$input = " <script>alert('xss')</script>  [email protected]  ";

// Encode for HTML output
$safe_html = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

// Remove HTML/PHP tags
$safe_tags = strip_tags($input);

// Trim whitespace
$clean_trim = trim($input);

// Sanitize email format
$safe_email = filter_var($input, FILTER_SANITIZE_EMAIL);

It's important to note that sanitizing user input does not guarantee that it is safe to use. You should always validate user input to ensure it meets your application's requirements and expected format before processing or storing it.

Dual-run preview — compare with live Symfony routes.