Preventing Cross-site Scripting by Sanitizing User Input

To sanitize user input before displaying it on a website and prevent cross-site scripting (XSS) attacks, you can use the PHP htmlspecialchars() function or the htmlentities() function. Here are a few examples using htmlspecialchars():

// Sanitize user input using htmlspecialchars() 
$username = htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8'); 
// Display the sanitized input on the website 
echo "Welcome, $username!";

In this example, the htmlspecialchars() function is used to sanitize the $_POST['username'] input. The second parameter (ENT_QUOTES) specifies that both single quotes and double quotes should be converted to their corresponding HTML entities. The third parameter specifies the character encoding used (in this case, UTF-8).

Similarly, here’s an example using htmlentities():

// Sanitize user input using htmlentities() 
$username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
// Display the sanitized input on the website
echo "Welcome, $username!";

In this example, the htmlentities() function is used to sanitize the $_POST['username'] input. Like htmlspecialchars(), the second parameter (ENT_QUOTES) specifies that both single quotes and double quotes should be converted to their corresponding HTML entities, and the third parameter specifies the character encoding used.

By using one of these functions to sanitize user input before displaying it on a website, any potentially malicious code in the input will be converted to harmless characters and prevent XSS attacks.