2

i am currently working on making my site injection proof and was wondering about the validations i am making, my code goes like this:

if(!empty($_POST['city']) && !empty($_POST['street'])){
  $city = htmlentities(mysql_real_escape_string($_POST['city']));
  $street = htmlentities(mysql_real_escape_string($_POST['street']));   
}

my question is isnt the empty check itself is a vulnerability? i mean do i have to escape string in the !empty validation as well? or it is safe to keep it that way? thanks.

antonpuz
  • 3,256
  • 4
  • 25
  • 48
  • There is no use `htmlentities`; and no, `empty` is not vulnerable, no need for escaping there – Pekka Jul 26 '13 at 11:48
  • It's fine. Learn about what an injection vulnerability actually is: [The Great Escapism (Or: What You Need To Know To Work With Text Within Text)](http://kunststube.net/escapism/). Also, why you're escaping too much. – deceze Jul 26 '13 at 11:48
  • htmlentities is redundant, if you keep worrying about the sql injection, just go to following URL. it has been asked and get the high rate answer http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php?rq=1 – Telvin Nguyen Jul 26 '13 at 11:51

2 Answers2

2

For SQL injection you only need to worry when quering the database, so isset is safe.

There should be no need for htmlentities (use it as protection against XSS).

mysql_real_escape_string will protect against SQL injection if done correctly, but should not be used at all, since the mysql_ prefix / DB-handler is outdated, deprecated and should not be used at all. The safest way is to use either mysqli_ or PDO, and use prepared statements.

Community
  • 1
  • 1
matino
  • 17,199
  • 8
  • 49
  • 58
2

SQL injection vulnerabilities work like this:

$username = $_GET["username"];

mysql_query("SELECT 1 FROM `users` WHERE `username` = '" . $username . "'");

Now if the value of $_GET["username"] is something like "foo' OR 1=1--"

The query:

SELECT 1 FROM `users` WHERE `username` = 'foo' OR 1=1
--'

will be run which selects all users

If you escape your input you will get the (intended) query:

SELECT 1 FROM `users` WHERE `username` = 'foo\' OR 1=1--'

PHP functions themselves aren't vulnerable.


Maybe this a good analogy: when someone says "Say your name" they want you to say "I'm John" not "your name"

Halcyon
  • 57,230
  • 10
  • 89
  • 128