我正在实现一个允许使用 MySQL 查询来过滤结果的系统。 “问题”是我需要检查查询是否包含一些 MySQL 命令以避免它们的执行(像 drop、delete、truncate 等命令)。 目前我的代码如下所示:
$query = "SELECT * FROM thetable";
$notAllowedCommands = array(
'DELETE',
'TRUNCATE',
'DROP',
'USE'
);
$containsNotAllowedCommands = false;
foreach($notAllowedCommands as $notAllowedCommand){
$upperCaseQuery = strtoupper($query);
if(strpos($upperCaseQuery, $notAllowedCommand) !== false){
$containsNotAllowedCommands = true;
break;
}
}
问题是,如果我添加以下查询:
SELECT * FROM USERS
strpos 将在 USERS(表名)中找到“USE”(命令)。
如果我使用别名或列名(例如 deleted_records)也是如此。
关于如何避免这种情况有什么建议吗?
提前致谢
编辑 看到建议后,这是我现在要实现的解决方案:
$containsNotAllowedCommands = false;
// Remove unwanted newlines and tabs and replace them with space.
$singleLineQuery = preg_replace("/[\r\n]+/", " ", $query);
// Convert the entire query to upper case (for comparison) and explode
$explodedQuery = explode(' ', strtoupper($singleLineQuery));
// Check if the intersection of both arrays is greater than zero
if(count(array_intersect($notAllowedCommands, $explodedQuery)) > 0){
$containsNotAllowedCommands = true;
}
我希望将来对其他人有用:D
谢谢大家!
最佳答案
你可以尝试一些类似的东西 -
$notAllowedCommands = array(
'DELETE',
'TRUNCATE',
'DROP',
'USE'
);
$query = "delete * FROM thetable";
if(preg_match('[' . implode(' |', $notAllowedCommands ) . ']i', $query) == true) {
echo 'true';
}
else
{
echo 'false';
}
preg_match
将检查字符串中的那些词。表达式将是 - [DELETE |TRUNCATE |DROP |USE]i
,它将检查那些带有尾随空格的单词,并且不区分大小写。
你也可以试试这个 -
$notAllowedCommands = array(
'DELETE',
'TRUNCATE',
'DROP',
'USE',
'delete',
'drop'
);
$query = "select * FROM users";
$temp= explode(' ', $query);
if(count(array_intersect($notAllowedCommands, $temp)) > 0)
{
echo "true";
}
else
{
echo "false";
}
关于php - 检查字符串是否包含 PHP 中不允许的 SQL 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34132575/