Appearance
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:
- 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. - 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. - 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. - 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. - Use
filter_var()with a specific filter flag to sanitize user input. For example, you can useFILTER_SANITIZE_EMAILto 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.