是" mysqli_real_escape_string"足以避免SQL注入或其他SQL攻击?

时间:2015-09-04 06:19:33

标签: php mysql security sql-injection

这是我的代码:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tool_bar"
        android:background="@color/light_blue"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <RelativeLayout android:id="@+id/action_home"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@drawable/touch_selector"
            android:clickable="true"
            android:padding="@dimen/small">
            <ImageView
                android:id="@+id/home_icon"
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:background="@drawable/white_square_icon"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:scaleType="fitCenter" />
            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:layout_toRightOf="@+id/home_icon"
                android:text="My App"
                android:textColor="@color/white_color"
                android:layout_marginLeft="@dimen/small"
                android:textSize="18sp" />
        </RelativeLayout>

    </android.support.v7.widget.Toolbar>

有人可以告诉我它是否安全,或者是否容易受到SQL注入攻击或其他SQL攻击?

1 个答案:

答案 0 :(得分:7)

  

有人可以告诉我它是否安全,或者是否容易受到SQL注入攻击或其他SQL攻击?

正如uri2x所说,请参阅SQL injection that gets around mysql_real_escape_string()

The best way to prevent SQL injection is to use prepared statements.他们将数据(您的参数)与指令(SQL查询字符串)分开,并且不会为数据留下任何污染查询结构的空间。准备好的语句解决了fundamental problems of application security之一。

对于无法使用预准备语句的情况(例如LIMIT),为每个特定目的使用非常严格的白名单是保证安全的唯一方法。

// This is a string literal whitelist
switch ($sortby) {
    case 'column_b':
    case 'col_c':
        // If it literally matches here, it's safe to use
        break;
    default:
        $sortby = 'rowid';
}

// Only numeric characters will pass through this part of the code thanks to type casting
$start = (int) $start;
$howmany = (int) $howmany;
if ($start < 0) {
    $start = 0;
}
if ($howmany < 1) {
    $howmany = 1;
}

// The actual query execution
$stmt = $db->prepare(
    "SELECT * FROM table WHERE col = ? ORDER BY {$sortby} ASC LIMIT {$start}, {$howmany}"
);
$stmt->execute(['value']);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

我认为即使在不起眼的边缘情况下,上述代码也不受SQL注入的影响。如果您正在使用MySQL,请确保您关闭模拟准备。

$db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
相关问题