SQL注入的正确修复?

时间:2013-06-08 13:19:13

标签: php mysql sql-injection

我的代码中有一个sql注入,我用havji检查了它。

所以我想到了一个修复,我将我的值的类型设置为整数或字符串 像这样。这会诀窍吗?不再注射???没什么好担心的 ? 我的代码在下面, 抱歉我的英文不好!

function get_page_by_id($page_id) {
    settype($page_id, "integer");

    global $connection;
    $query = "SELECT * ";
    $query .= "FROM pages ";
    $query .= "WHERE id=" . $page_id ." ";
    $query .= "LIMIT 1";
    $result_set = mysql_query($query, $connection);
    confirm_query($result_set);
    // REMEMBER:
    // if no rows are returned, fetch_array will return false
    if ($page = mysql_fetch_array($result_set)) {
        return $page;
    } else {
        return NULL;
    }
}

修复前的代码

function get_page_by_id($page_id) {

    global $connection;
    $query = "SELECT * ";
    $query .= "FROM pages ";
    $query .= "WHERE id=" . $page_id ." ";
    $query .= "LIMIT 1";
    $result_set = mysql_query($query, $connection);
    confirm_query($result_set);
    // REMEMBER:
    // if no rows are returned, fetch_array will return false
    if ($page = mysql_fetch_array($result_set)) {
        return $page;
    } else {
        return NULL;
    }
}

2 个答案:

答案 0 :(得分:0)

您通常要做的是使用预备语句。对于php,您可以阅读一个选项here

以下是该页面的示例

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

答案 1 :(得分:-1)

请尝试以下代码:

$page_id = mysql_real_escape_string(stripslashes($page_id));