Sample code to fix this particular SQL-injection hole

我只是一个虾纸丫 提交于 2019-12-11 03:21:57

问题


Please read fully first

In this answer: How to prevent SQL injection with dynamic 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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6051125/sample-code-to-fix-this-particular-sql-injection-hole

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!