0

I'm a beginner in PHP and I only know some basic things. Months ago, I started working on a "blog" platform, and created a login system based on PHP and MySQL. To make it more secure, I encrypted the passwords and used mysqli_real_escape_string() on the variables present in the login form ($username, $password).

I read something about some kind of "prepared statements", and I've got a question: why are they considered "better" than mysqli_real_escape_string()? Why should I use them, instead of the function mentioned above?

Looked for an answer, and didn't find any (only people that constantly said that it is 'just better'), so I decided to ask the question here.

mmateas
  • 50
  • 8
  • Just as a bit of extra information, for passwords the recommended way is https://stackoverflow.com/questions/30279321/how-to-use-phps-password-hash-to-hash-and-verify-passwords – Nigel Ren May 06 '20 at 07:00
  • 2
    The answer is simple: contrary to a widespread superstition, mysqli_real_escape_string *has noting to do with security* and therefore should never be used for the purpose. – Your Common Sense May 06 '20 at 07:02
  • @NigelRen Thanks for the tip. But I don't understand the reason you've closed my question. I don't find any proper answer there. I've literally checked every question here, and didn't find any proper answer. The link you provided only contains answers such as: "Use prepared statements because after using this you doesn't have to use mysqli_real_escape_string. prepared statements doing this as by default." – mmateas May 06 '20 at 07:03
  • 2
    The problem with SQL injection is that _code_ (SQL syntax) and _data_ are mixed together in an SQL statement you execute “normally”, so by manipulating the input data, I can attack your system, if your escaping measures fail in some way - because I can make the data I send _become_ code. Prepared statements do not mix both to begin with - the statement gets prepared first, based on code that does _not_ have any data inserted into it. The data is then send separately, afterwards. So the danger of data being mistaken _for_ code by the query parser does not exist here any more. – CBroe May 06 '20 at 07:14
  • I've added another duplicate which shows how to get round `mysqli_real_escape_string()` in your SQL. – Nigel Ren May 06 '20 at 07:30
  • 1
    @NigelRen I moved this link into a comment https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string bacause single duplicate will cause a redirect while multiple will leave this question to hang around. – Your Common Sense May 06 '20 at 07:55
  • @YourCommonSense, OK - I will try and remember that in future. – Nigel Ren May 06 '20 at 07:56
  • 1
    Hope it will shed some light: https://phpdelusions.net/articles/why_should_i_use_prepared_statements_if_escaping_is_safe – Your Common Sense May 06 '20 at 08:52

0 Answers0