PHP

Prevent Cross-Site Scripting (XSS) with PHP Output Escaping

Secure your web applications against XSS attacks by properly escaping user-generated content before rendering it in HTML using PHP's htmlspecialchars().

<?php
/**
 * Safely escapes a string for HTML output to prevent XSS attacks.
 *
 * @param string|null $input The string to escape.
 * @return string The escaped string.
 */
function escapeHtml(string $input = null): string
{
    if ($input === null) {
        return '';
    }
    // ENT_QUOTES: Converts both double and single quotes.
    // UTF-8: Specifies the character encoding.
    return htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}

// --- Usage Example ---
$userInput = "<script>alert('You are hacked!');</script>";
$commentText = "This is a user comment with some <b>bold</b> text.";
$attributeValue = 'onmouseover="alert(\'Malicious event\')"';

echo "<h3>Original User Input:</h3>";
echo $userInput . "

";

echo "<h3>Escaped User Input (safe for HTML):</h3>";
echo escapeHtml($userInput) . "

";

echo "<h3>User Comment (safe for display):</h3>";
echo escapeHtml($commentText) . "

";

// Example of using escaped data within an HTML attribute
echo "<button data-user-info='" . escapeHtml($attributeValue) . "'>Click Me</button>
";

// Output for demonstration (view source to see escaped HTML)
// <button data-user-info='onmouseover=&quot;alert(&#039;Malicious event&#039;)&quot;'>Click Me</button>
?>
How it works: This snippet demonstrates a fundamental XSS prevention technique: output escaping. It uses PHP's `htmlspecialchars()` function to convert special characters (like `<`, `>`, `&`, `"`, `'`) into their HTML entities before rendering user-generated content to the browser. This prevents malicious scripts embedded in user input from being executed, ensuring that the browser interprets the input as plain text rather than executable code. Always escape data directly before outputting it to the HTML context.

Need help integrating this into your project?

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

Hire DigitalCodeLabs