How can I prevent XSS with HTML/PHP?

How can I prevent XSS with HTML/PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Single Rule for Preventing XSS in HTML and PHP

Cross-site scripting (XSS) occurs when untrusted data is sent to a webpage without proper validation or escaping, allowing attackers to inject malicious scripts into other users' browsers. Preventing this vulnerability using only HTML and PHP relies on one fundamental principle: always escape output.

The core mechanism is straightforward. When you retrieve data from a database, form field, or API call in PHP, that data is treated as plain text until it reaches the browser. The browser, however, expects specific characters to mean specific things within an HTML document. If a user inputs <script>alert('XSS')</script> and your code echoes that string directly into an <img> tag like src="<?php echo $input; ?>", the browser parses the input not as text, but as executable code.

To prevent this, you must ensure that special characters are rendered literally to the user rather than being interpreted as HTML markup or script. In PHP, this is handled by the htmlspecialchars() function. This function converts certain characters—specifically <, >, &, ', and "—into their corresponding HTML entities (e.g., < becomes &lt;).

// Vulnerable: Direct echo without escaping
echo "<img src='" . $user_input . "' alt='Profile Picture'>";

// Secure: Using htmlspecialchars with appropriate flags
echo '<img src="' . htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8') . '" alt="Profile Picture">';

The second argument, ENT_QUOTES, is critical. It ensures that both single quotes and double quotes are escaped. If you omit this or use only ENT_NOQUOTES, an attacker can break out of a string delimited by the unescaped quote character. The third argument must be 'UTF-8' to ensure consistent behavior across different environments and to prevent encoding-based bypasses.

A common pitfall is assuming that cleaning input data at the point of entry (e.g., using strip_tags() or regex) is sufficient. This approach is flawed because it relies on the attacker following your assumptions about what constitutes valid input. Instead, you must assume all input is hostile and sanitize every single output location independently. For example, if $user_input contains <b>Bold</b>, echoing it directly will render bold text. If you echo it inside an attribute value without escaping the quotes, the attribute closes prematurely, allowing a script to execute.

Sometimes developers use htmlentities() instead of htmlspecialchars(). While similar, htmlentities() converts all non-ASCII characters into entities as well. This is often unnecessary overhead and can introduce issues with UTF-8 encoding if not handled carefully. Stick to htmlspecialchars() for HTML content attributes and body text unless you have a specific requirement to encode the entire character set.

Context matters significantly. You must apply the correct escaping strategy based on where the data is being placed:

  • HTML Body Text: Use htmlspecialchars() with ENT_QUOTES. This prevents script injection while allowing standard text to render correctly.
  • HTML Attributes: Also use htmlspecialchars() with ENT_QUOTES. Even inside quotes, the single or double quote character can break the attribute syntax.
  • JavaScript Contexts: If you are embedding data into a <script> tag or inline event handlers (like onclick), htmlspecialchars() is insufficient because it does not escape forward slashes or backticks which might be valid in JavaScript strings depending on the quoting style. For JS contexts, use json_encode() for JSON data or manually escape quotes and backslashes specifically for that context.

Relying solely on HTML sanitization libraries without understanding the underlying escaping logic is a recipe for failure. The most robust defense remains consistent application of output encoding at every point where user data leaves your server.

Our network