Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need htmlentities() or htmlspecialchars() in prepared statements?

Tags:

php

mysql

In an article http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html, it says the followings:

There are numerous advantages to using prepared statements in your applications, both for security and performance reasons.

Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack.

Normally when you are dealing with an ad hoc query, you need to be very careful when handling the data that you received from the user. This entails using functions that escape all of the necessary trouble characters, such as the single quote, double quote, and backslash characters.

This is unnecessary when dealing with prepared statements. The separation of the data allows MySQL to automatically take into account these characters and they do not need to be escaped using any special function.

Does this mean I don't need htmlentities() or htmlspecialchars()? But I assume I need to add strip_tags() to user input data? Am I right?

like image 287
shin Avatar asked Aug 02 '09 16:08

shin


1 Answers

htmlentities and htmlspecialchars are used to generate the HTML output that is sent to the browser.

Prepared statements are used to generate/send queries to the Database engine.

Both allow escaping of data; but they don't escape for the same usage.
So, no, prepared statements (for SQL queries) don't prevent you from properly using htmlspecialchars/htmlentities (for HTML generation)

About strip_tags: it will remove tags from a string, where htmlspecialchars will transform them to HTML entities.
Those two functions don't do the same thing; you should choose which one to use depending on your needs / what you want to get.

For instance, with this piece of code:

$str = 'this is a <strong>test</strong>';
var_dump(strip_tags($str));
var_dump(htmlspecialchars($str));

You'll get this kind of output:

string 'this is a test' (length=14)
string 'this is a &lt;strong&gt;test&lt;/strong&gt;' (length=43)

In the first case, no tag; in the second, properly escaped ones.

And, with an HTML output:

$str = 'this is a <strong>test</strong>';
echo strip_tags($str);
echo '<br />';
echo htmlspecialchars($str);

You'll get:

this is a test
this is a <strong>test</strong>

Which one of those do you want? That is the important question ;-)

like image 88
Pascal MARTIN Avatar answered Oct 24 '22 03:10

Pascal MARTIN