How to print user text safely
Short answer
Pass everything you print into HTML through htmlspecialchars():
<?php
$comment = '<script>alert(1)</script>';
echo htmlspecialchars($comment);Output:
<script>alert(1)</script>With line breaks
Escape first, then nl2br():
<?php
$comment = "First line\n<b>Second</b>";
echo nl2br(htmlspecialchars($comment));Output:
First line<br />
<b>Second</b>An attribute value
Quotes in the value are escaped too — the form field does not "break":
<?php
$name = 'Tom "The Cat"';
echo '<input value="' . htmlspecialchars($name) . '">';Output:
<input value="Tom "The Cat"">Functions used in this recipe
- htmlspecialchars — Replaces HTML special characters with safe entities.
- strip_tags — Removes HTML tags from a string.
- nl2br — Inserts a br tag before every line break.