保护mysql数据库查询免受sql注入

时间:2015-05-20 09:55:11

标签: php mysql database

我是一名php安全菜鸟。我在我的网站上有两件事我查询我的数据库(它只包含有关组成我网站的页面的信息,例如标题,关键字......)

a)我动态创建菜单。我通过url传递一个变量,然后将其舀起并在查询中使用它,如下所示:

User clicks on subpage.php?someid=12

我查询数据库:

    if(isset($_GET["someid"])) {
if (preg_match('/[0-9]+/', $_GET["someid"])) {
        $input = mysqli_real_escape_string($connect, $_GET["someid"]);
        $sql_3 = "SELECT link, title FROM pages WHERE parent_page = ".$input."";

这样安全吗?

b)我有一点关键字搜索。我的数据库表包含带有关键字的文本字段。用户可以在输入字段中输入几个关键字,然后查询数据库:

if(isset($_POST["keywords"])) {

    if (preg_match('/^([a-zA-Z\-0-9]+(?:\s|$))+$/', $_POST["keywords"])) {
        $input = mysqli_real_escape_string($connect, $_POST["keywords"]);
        $sql_8 = 'SELECT id FROM pages WHERE match(keywords) against ("'.$input.'")'; 

这样安全吗?

感谢您的提示和帮助!

1 个答案:

答案 0 :(得分:1)

只需在连接字符串后面添加以下行。

/*Start Security Purpose*/
if (get_magic_quotes_gpc()) {
    function stripslashesGpc(&$value)
    {
        $value = stripslashes($value);
    }
    array_walk_recursive($_GET      , 'stripslashesGpc');
    array_walk_recursive($_POST     , 'stripslashesGpc');
    array_walk_recursive($_COOKIE   , 'stripslashesGpc');
    array_walk_recursive($_REQUEST  , 'stripslashesGpc');
}
//Prevent Sql Injection
$_POST = isset($_POST)?$_POST:"";
array_walk($_POST, function(&$string) use ($conn) { $string = mysqli_real_escape_string($conn, $string);});
/*End Security Purpose*/

您可以查看https://github.com/jewelhuq/Simple-php-crud-project/blob/master/dbconnect.php

相关问题