开发者

Sample code to fix this particular SQL-injection hole

开发者 https://www.devze.com 2023-03-06 17:20 出处:网络
Please read fully first In this answer: How to prevent SQL injection with dyna开发者_JS百科mic tablenames?

Please read fully first

In this answer: How to prevent SQL injection with dyna开发者_JS百科mic tablenames?

Pekka points out why this code:

$clas=$_POST['clas'];
$query="SELECT * FROM $clas ";

Cannot be repaired by using a PDO or mysql-real_escape_string().

Can anyone please provide sample code how to fix this so a newbie can paste that code

(after/adjusting it to his needs) and be safe from SQL-injection.

Please don't explain SQL-injection, I know all about injection and PDO, I just need sample code


You could use a whitelist to ensure that the value is indeed one of the tables you wish to be accessed in that way.

Example:

$allowed_tables = array('table1', 'table2');
$clas = $_POST['clas'];
if (in_array($clas, $allowed_tables)) {
    $query = "SELECT * FROM `$clas`";
}

Note that constructing SQL queries directly from GET or POST parameters is usually a bad idea anyways, but a whitelist can make it safe.


You can use the for escape :P

$clas = str_replace('`','\\`',$_POST['clas']);
$query = "SELECT * FROM \`{$clas}\`";

So, is a ver very bad idea.

Do it different.

0

精彩评论

暂无评论...
验证码 换一张
取 消