How to Sanitize Data for XSS PHP
XSS is a security vulnerability in Web applications that is exploited by hackers to gain access to a user's personal information, to impersonate another user or to gain access to a Web server with elevated privileges. Set up precautions for your PHP programs to sanitize user input to prevent XSS attacks.
Instructions
-
-
1
Use the "htmlspecialchars" function to sanitize external input where you might allow HTML markup in the input. Call the function to replace the "less than" and "greater than" signs with HTML codes "<" and ">" to thwart an attempt to inject a malicious script with the "<script>" tag. For example:
echo htmlspecialchars($userinput);
-
2
Insert the "striptags" function to eliminate HTML tags where no HTML markup would be allowed. Don't use "striptags" in cases where legitimate uses of HTML would be allowed, or it may lead to data loss. For example:
echo "Cannot log in with the username " . striptags($_GET['username']); // no HTML code allowed in a user name
-
-
3
Use double quotation marks to surround HTML attributes involving user input. Pass the "ENT_QUOTES" parameter to the "htmlspecialchars" function. This provides additional protection against attacks that will exploit injecting code into HTML attributes that use single instead of double quotation marks. For example:
<img src="loaded.png" alt='<?php echo htmlspecialchars($user_description, ENT_QUOTES);?>' />
<img src="loaded.png" alt="<?php echo htmlspecialchars($user_description)_;?>" />
-
4
Call the "urlencode" function for maximum protection in sanitizing data that may appear as an HTML attribute. It takes a more aggressive approach to converting potentially harmful characters. For example:
<input type="text" value="<?php echo urlencode($user_input);?>" />
-
5
Utilize the "mysqlrealescapestring" function to sanitize input before using it in database operations with the "mysql" extension to prevent SQL injection attacks. For example:
$query = 'SELECT * FROM data WHERE usercriteria="' . mysqlrealescapestring($usercriteria) . '"';
-
6
Use the "mysqli" extension instead of "mysql" along with prepared statements to have the extension escape user input for you and prevent SQL injection attacks. For example:
$stmt = $mysqli->prepare("SELECT * FROM data WHERE usercriteria=?");
$stmt->bind_param('s', $usercriteria);
$stmt->execute();
-
1