Skip to content

Escape Output

XSS is a security vulnerability where attackers inject malicious scripts into web pages. When users visit the page, the script runs in their browser and can steal cookies, session data, or perform actions on their behalf.


Output escaping converts dangerous characters (like <, >, ", ') into safe HTML entities before displaying them. This prevents injected scripts from executing.

For example:

  • <script> becomes &lt;script&gt;
  • The browser displays the text instead of running it as code

Use htmlspecialchars() to escape any dynamic content:

$userInput = "<script>alert('XSS!');</script>";
$safe = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $safe;
// Displays: &lt;script&gt;alert(&#039;XSS!&#039;);&lt;/script&gt;

Always use these parameters:

  • ENT_QUOTES - Escapes both single and double quotes
  • 'UTF-8' - Proper character encoding

Escape output, not input. Store raw data in the database, escape when displaying.

// Store raw data
$comment = $_POST['comment'];
$stmt->execute(['comment' => $comment]);
// Escape when displaying
echo htmlspecialchars($row['comment'], ENT_QUOTES, 'UTF-8');

// Helper function for escaping
function e($string) {
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
// Display user data safely
echo "<p>Welcome, " . e($username) . "</p>";
echo "<p>Your comment: " . e($comment) . "</p>";

Always escape all dynamic content - even data from your database.