Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Htmlentities vs addslashes vs mysqli_real_escape_string

I've been doing some reading on securing PHP applications, and it seems to me that mysqli_real_escape_string is the correct function to use when inserting data into MySQL tables because addslashes can cause some weird things to happen for a smart attacker. Right?

However, there is one thing that is confusing me. I seem to remember being advised addslashes is better than htmlentities when echoing user-entered data back to users to protect their data, but it seems like addslashes is the one with the vulnerability. Is this true, or am I remembering incorrectly?

like image 455
waiwai933 Avatar asked Feb 06 '10 18:02

waiwai933


2 Answers

They are different tools for different purposes.

mysqli_real_escape_string makes data safe for inserting into MySQL (but parametrized queries are better).

Htmlentities makes data safe for outputting into an HTML document

addslashes makes data safe for a few other situations, but is insufficient for MySQL

like image 107
Quentin Avatar answered Oct 02 '22 03:10

Quentin


There are different contexts for your data. The context of inserting data into the database needs to be escaped differently than the context of rendering html/xml or even an email message.

Escaping data going into a db should be deprecated in all new code in favor of prepared statements. Anyone who tells you otherwise is doing you a great disservice.

Escaping data going to the browser needs to be escaped in a number of different ways depending on the target. Sometimes htmlspecialchars is enough, sometimes you need to use htmlentities. Sometimes you need numeric entities. It is a topic you should do some research on to know all of the nuances.

The general rule I live by is validate (not filter, reject if incorrect) input & escape output (based on context).

like image 21
Eric Butera Avatar answered Oct 02 '22 03:10

Eric Butera