Security with htmlspecialchars()
Learn to close the XSS hole from user input with htmlspecialchars().
XSS and htmlspecialchars()
Printing user data straight to the screen creates an XSS (Cross-Site Scripting) hole. If a malicious user types <script>alert('bad')</script> in a form field, it runs as is. htmlspecialchars() turns <, >, &, " and ' into HTML entities; the browser then shows them as text instead of running them as code.
Example: echo htmlspecialchars($_POST['name']);. The input <script> comes out as <script>; harmless.
The ENT_QUOTES flag
By default htmlspecialchars() turns the double quote into " but leaves the single quote alone. To convert single quotes too, pass the ENT_QUOTES flag: htmlspecialchars($text, ENT_QUOTES). Now both " and ' are safe.
This matters especially for values placed inside an attribute: value="<?php echo htmlspecialchars($name, ENT_QUOTES); ?>". Otherwise an input like ' onclick='alert(1) can break out of the attribute.
Exercise Stop XSS with htmlspecialchars
Set $_POST['comment'] = "<script>alert(1)</script>";. Then write echo htmlspecialchars($_POST['comment'], ENT_QUOTES);.
Show example solution
First set $_POST['comment'] = "<script>alert(1)</script>";. Then write echo htmlspecialchars($_POST['comment'], ENT_QUOTES);
Example solution:
<?php
// Stop XSS with htmlspecialchars
$_POST['comment'] = "<script>alert(1)</script>";
echo htmlspecialchars($_POST['comment'], ENT_QUOTES);
Test yourself
-
What does htmlspecialchars() do?
- It deletes form data
- It destroys HTML tags
- It validates the form
- It converts special characters to HTML entities
Show answer
It converts special characters to HTML entities — Correct. htmlspecialchars turns <, >, &, ", ' into safe HTML entities.
-
Match each character to its HTML entity
- <
- <
- >
- >
- &
- &
- "
- "
-
Escape with htmlspecialchars
echo ____($_POST['comment']);Show answer
echo htmlspecialchars($_POST['comment']);