-2

I have seen in many source codes where developers used curly braces on the user input variable for ex:-

query("SELECT * FROM users WHERE email = '{$email}' AND password = '{$password}'");

And I have seen that people created two files (for may be some reasons) one with this query: retrieve.php

query("SELECT * FROM users WHERE email = $email AND password = $password");

and other file with this query: retrieve_safely.php (note the filename)

query("SELECT * FROM users WHERE email = '{$email}' AND password = '{$password}'");

Now this creates a doubt to me, what is this difference between these two? What is the exact use for the curly braces in the query? Are they use to prevent from SQL injection? If so, how it can be?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • does this answer your question https://stackoverflow.com/questions/2596837/curly-braces-in-string-in-php or this https://stackoverflow.com/questions/5370426/how-does-affect-a-mysql-query-in-php – Aqib Javed Mar 03 '22 at 06:36
  • https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex – Rylee Mar 03 '22 at 06:55
  • 1
    What a horrible background to work/learn in it must be where you would chance to see such files! retrieve.php with SQL syntax error and retrieve_safely.php is not safe at all – Your Common Sense Mar 03 '22 at 07:06
  • Unless the first SQL statement had `$email` defined as `$email = "'$email'";` or so, it would invariably fail, because strings must be quoted for a SQL statement, and I'm guessing that email and password are _not_ going to be integers. The second one would be "safe" from failing, but it is in no other way safe. In positive prospects, you'll get to write a lot of things from a scratch. No need to put too much effort into understanding old code, unless for "how not to". ^_^ – Markus AO Mar 03 '22 at 07:56

1 Answers1

2

TL;DR: NO, IT DOES NOT PREVENT SQL INJECTION

The curly braces are a way to inject variable's content into the string. Reference: https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

So this two commands do exactly the same thing:

query("SELECT * FROM users WHERE email = $email AND password = $password");
query("SELECT * FROM users WHERE email = {$email} AND password = {$password}");

If it's the same, then why bother with curly braces? Because it's a way to inject an object's property/data member into string:

query("SELECT * FROM users WHERE email = {$user->email} AND password = {$user->password}");

By reading the filename retrieve.php and retrieve_safely.php, there's a difference that there's a quote around the variable in _safely file.

So, unless there's a kind of input sanitization before the code in retrieve_safely.php, that file is no more safe than retrieve.php

Kristian
  • 2,456
  • 8
  • 23
  • 23