Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use htmlspecialchars() function?

Hi I was wondering when is the appropriate place to use htmlspecialchars(). Is it before inserting data to database or when retrieving them from the database?

like image 245
khr2003 Avatar asked Feb 03 '11 03:02

khr2003


People also ask

When should you use the Htmlspecialchars function?

The htmlspecialchars() function is used to converts special characters ( e.g. & (ampersand), " (double quote), ' (single quote), < (less than), > (greater than)) to HTML entities ( i.e. & (ampersand) becomes &amp, ' (single quote) becomes &#039, < (less than) becomes &lt; (greater than) becomes &gt; ).

What's the difference between HTML entities () 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.

What does Htmlspecialchars return?

This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.


2 Answers

You should only call this method when echoing the data into HTML.

Don't store escaped HTML in your database; it will just make queries more annoying.
The database should store your actual data, not its HTML representation.

like image 56
SLaks Avatar answered Sep 22 '22 02:09

SLaks


You use htmlspecialchars EVERY time you output content within HTML, so it is interperted as content and not HTML.

If you allow content to be treated as HTML, you have just opened the door to bugs at a minimum, and total XSS hacks at worst.

like image 44
gahooa Avatar answered Sep 25 '22 02:09

gahooa