Search code examples
phpmysqlsql-injection

Does this counts as bug for php


consider this code

<?
if($_GET["inp"]==0 || $_GET["inp"]==1) $inp=$_GET["inp"];
mysql_query("select * from table1 where field1=".$inp);
?>

and php returns this statement $_GET["inp"]==0 always true unless we use $_GET["inp"]=="0"

So if someone use this code, He can be hacked by sql-injection. Does this counts as bug?


Solution

  • No it is no bug

    $_GET["inp"]==0
    

    should be

    $_GET["inp"]==="0"
    

    === means you check the data type. Take a look here: http://php.net/manual/de/language.operators.comparison.php

    Also please take a look at pdo (http://php.net/manual/de/book.pdo.php) and prepared statements. (SQL Injection is possible with your code)

    Why should "everything"==0 return true? Yes I know about === but even == must not retrun true. – Mehdi Azizi

    From the docs here: http://php.net/manual/en/language.operators.comparison.php

    If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

    With this info we can convert this:

    var_dump(0 == "a"); //true
    //a is not a real number, so we use 0
    var_dump(0 == 0); //true
    

    What we want:

    //Note it is === and not ==
    var_dump(0 === "a"); //false
    

    Also interessting

    var_dump("true" == 0); //false
    var_dump("true" == 1); //false
    var_dump("false" == 0); //false
    var_dump("1" == 1); //true
    var_dump("1" == 0); //false
    var_dump("0" == 0); //true
    

    And for prevention

    var_dump(empty("")); //true
    var_dump(empty(0)); //true
    var_dump(empty(null)); //true
    var_dump(empty(false)); //true
    var_dump(empty(true));  //false
    

    You want to check "real" empty, you use ($var === ''). PHP is a very old language with many design fails.