← Back to all snippets
PHP

Securely Output User Input to Prevent XSS

Learn to prevent Cross-Site Scripting (XSS) attacks by securely encoding user-generated data before rendering it in HTML, using PHP's htmlspecialchars.

<?php
function secureOutput($data) {
    return htmlspecialchars($data, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}

// Example usage:
$userComment = "<script>alert('XSS Attack!');</script> Your comment here.";
$userName = "John Doe <img src='x' onerror='alert(\"XSS!\")'>";

echo "<h3>User Comment:</h3>";
echo "<p>" . secureOutput($userComment) . "</p>";

echo "<h3>User Name:</h3>";
echo "<span>" . secureOutput($userName) . "</span>";

// Expected output for demonstration (HTML encoded):
// <h3>User Comment:</h3><p>&lt;script&gt;alert(&#039;XSS Attack!&#039;);&lt;/script&gt; Your comment here.</p>
// <h3>User Name:</h3><span>John Doe &lt;img src=&#039;x&#039; onerror=&#039;alert(&quot;XSS!&quot;)&#039;&gt;</span>
?>
How it works: This snippet demonstrates how to prevent Cross-Site Scripting (XSS) by encoding special characters in user-generated input before displaying it in HTML. The `htmlspecialchars` function in PHP converts characters like `<`, `>`, `&`, `"`, and `'` into their corresponding HTML entities. This ensures that the browser interprets the input as plain text rather than executable code, effectively neutralizing XSS attempts. The `ENT_QUOTES | ENT_HTML5` flags ensure both single and double quotes are handled and uses the HTML5 doctype.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs