PHP htmlspecialchars (original) (raw)

Skip to content

Summary: in this tutorial, you’ll learn how to use the PHP htmlspecialchars() function to prevent XSS attacks.

What Is XSS? #

XSS stands for cross-site scripting. It’s a kind of attack where a hacker injects malicious client code into a web page’s output.

For example, if you have a form that allows users to submit comments and display them on the page. If you display the comments without any processing, your page is vulnerable to the XSS attack.

A hacker may submit a comment with JavaScript code that redirects users to a malicious website. For example:

<script>location.replace('<malicious website url>');</script>Code language: PHP (php)

This comment contains a JavaScript code that redirects the users to a malicious website.

If you store this comment in the database and display it in the comments section. When legitimate users visit the page, the JavaScript code will execute and redirect the users to the malicious website.

To prevent XSS attacks, you should always escape the string from unknown sources such as user inputs. To escape a string for output, you use the htmlspecialchars() function.

Introduction to the PHP htmlspecialchars() function #

The htmlspecialchars() function accepts an input string ($string) and returns the new string with the special characters converted into HTML entities.

htmlspecialchars ( string $string , int $flags = ENT_COMPAT , string|null $encoding = null , bool $double_encode = true ) : stringCode language: PHP (php)

The function accepts four parameters:

The following table shows the special characters that the htmlspecialchars() function will convert to HTML entities:

Character Name Replacement
& Ampersand &
" Double quote ", unless ENT_NOQUOTES is set
' Single quote ' (for ENT_HTML401 flag) or ' (for ENT_XML1, ENT_XHTML or ENT_HTML5 flag), but only when ENT_QUOTES flag is set
< Less than <
> Greater than >

PHP htmlspecialchars() function example #

The following example shows how to display a string on a page without escaping:

`<?php

$comment = ""; echo $comment;`Code language: PHP (php)

If you run the code on a web browser, you’ll see an alert message.

To escape the $comment string, you use the htmlspecialchars() function as follows:

`<?php

$comment = ''; echo htmlspecialchars($comment);`Code language: PHP (php)

Try it

Now, you’ll see the following string on the webpage instead:

<script>alert("Hello there");</script>Code language: PHP (php)

The htmlspecialchars function converts the $comments to the following:

&lt;script&gt;alert(&quot;Hello there&quot;);&lt;/script&gt;Code language: PHP (php)

Summary #

Did you find this tutorial useful?