Prevent injection SQL with PHP [duplicate]

2019-05-26 22:44发布

问题:

This question already has an answer here:

  • How can I prevent SQL injection in PHP? 28 answers

Since my statements are like

"SELECT * FROM `box` WHERE `thing` = '{$variable}'

Could I clean that with simply

$variable = str_replace("'","\'",$variable);
"SELECT * FROM `box` WHERE `thing` = '{$variable}'

Would that work? My host doesn't support mysql escape and I'm not using mysqli.

回答1:

Depending on what classes as a valid data type for your query, you can usually get away with:

function cleanVar($str){
    $str = strip_tags(addslashes($str));
    return $str;
}


回答2:

Use parametrized queries (PDO is probably your best bet).



回答3:

I highly doubt that your host doesn't support the mysql_real_escape_string function.

$variable = mysql_real_escape_string($variable);

$sql = "SELECT * FROM `box` WHERE `thing` = '{$variable}'";

If indeed you don't have MySQL installed, then you can use one of the following escape functions based on which RDBMS you're using:

pg_escape_string

sqlite_escape_string

db2_escape_string

ingres_escape_string



回答4:

If it's postgres you can use pg_escape_string.



回答5:

Hate to repeat myself, but, once again, try this one:
PHP Intrusion Detection System