Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htmlspecialchars vs htmlentities when concerned with XSS

Tags:

php

xss

I have seen a lot of conflicting answers about this. Many people love to quote that php functions alone will not protect you from xss.

What XSS exactly can make it through htmlspecialchars and what can make it through htmlentities?

I understand the difference between the functions but not the different levels of xss protection you are left with. Could anyone explain?

like image 627
stuckinphp Avatar asked Sep 02 '10 01:09

stuckinphp


People also ask

Is Htmlentities enough to prevent XSS?

htmlentities vs htmlspecialcharsBoth will prevent XSS attacks. The difference is in the characters each encodes.

Is Htmlspecialchars enough for XSS?

are there any cases where htmlspecialchars($input, ENT_QUOTES, 'UTF-8') (converting & , " , ' , < , > to the corresponding named HTML entities) is not enough to protect against cross-site scripting when generating HTML on a web server? Yes, this is only about HTML output.

What's the difference between Htmlentities () and htmlspecialchars ()?

Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is that htmlspecialchars() function convert the special characters to HTML entities whereas htmlentities() function convert all applicable characters to HTML entities.

Is Htmlentities secure?

No, functions like htmlspecialchars and htmlentities do not protect against all cases of Cross-Site Scripting.


1 Answers

htmlspecialchars() will NOT protect you against UTF-7 XSS exploits, that still plague Internet Explorer, even in IE 9: http://securethoughts.com/2009/05/exploiting-ie8-utf-7-xss-vulnerability-using-local-redirection/

For instance:

<?php $_GET['password'] = 'asdf&ddddd"fancy˝quotes˝';  echo htmlspecialchars($_GET['password'], ENT_COMPAT | ENT_HTML401, 'UTF-8') . "\n"; // Output: asdf&amp;ddddd&quot;fancyË  echo htmlentities($_GET['password'], ENT_COMPAT | ENT_HTML401, 'UTF-8') . "\n"; // Output: asdf&amp;ddddd&quot;fancy&Euml;quotes 

You should always use htmlentities and very rarely use htmlspecialchars when sanitizing user input. ALso, you should always strip tags before. And for really important and secure sites, you should NEVER trust strip_tags(). Use HTMLPurifier for PHP.

like image 188
Theodore R. Smith Avatar answered Sep 28 '22 03:09

Theodore R. Smith