Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ;-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...