htmlspecialchars in PHP

htmlspecialchars is a PHP function that serves to provide security against cross-site scripting (XSS) attacks. This function was added in PHP version 4.3.0 and has better recursion protection than the htmlentities function, the difference between both being that htmlentities translates everything except < and & into HTML entities while htmlspecialchars doesn’t translate these two characters but instead escapes them using \ as a prefix.

What is XSS?

Cross-site Scripting (XSS) is a type of vulnerability that allows attackers to inject malicious code into your site. These scripts allow them to modify HTML page content, steal data or lead the user to another website.

PHP htmlspecialchars() function

We use it to convert our special characters into HTML entities, Let’s see how it works.

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

Example:

<?php

$PHP = "<script>alert('PHP Error Code');</script>";

echo $PHP;

When you will run it so it will show as an alert message, Message will be PHP ERROR Code. But if you want to escape this you have to use the htmlspecialchars() function as we are using here.

<?php

$PHP = '<script>alert('PHP Error Code');</script>';

echo htmlspecialchars($PHP);

Now it will not alert it, it will simply show this on your web page as like:

<script>alert('PHP Error Code');</script>

Conclusion

In this article, We defined XSS attack and how can we escape string while showing it on the webpage to stay safe from XSS attack.

Suggested Articles:

Leave a Comment