Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

&lt;script&gt;alert(1)&lt;/script&gt;

With line breaks

Escape first, then nl2br():

<?php
 
$comment = "First line\n<b>Second</b>";
 
echo nl2br(htmlspecialchars($comment));

Output:

First line<br />
&lt;b&gt;Second&lt;/b&gt;

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 &quot;The Cat&quot;">

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.

Thanks for reading!

Donate to the site — we work hard for you.