SQL注入是一种代码注入技术,用通过表单域插入的恶意SQL语句来攻击Web应用程序,并且通常会提取重要的数据库信息。这是一个非常关键的安全漏洞,它可以完全破坏数据库,所以最需要使用适当的代码来保护应用程序。

本文章向大家介绍php有效防止SQL注入攻击的三种方法。

 

方法一:使用转义字符串mysql_real_escape_string

开发人员通常使用PHP函数mysql_real_escape_string来过滤输入数据。从PHP 5.5.0起,mysql_real_escape_string和mysql扩展名已被弃用。所以我们将使用mysqli extension和mysqli :: escape_string函数。其中不必要的额外字符被删除然后传递给执行

$uid= mysqli_real_escape_string($uid);

//   method of calling
$uid= $mysqli->escape_string($uid);

php实例代码:

<?php
    
    //  Full Sample code
    //	Creating connection and checkng for errors
    //	Error Statement
    //	Escaping the string and execution
    
    
    /* create connection */
    $mysqli = new mysqli(\"localhost\", \"username\", \"password\", \"data \");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf(\"Connect failed: %s\\n\", mysqli_connect_error());
        exit();
    }


    $city = \"\'s hyderabad\";

    /* this query will fail, because we didn\'t escape $city */
    if (!$mysqli->query(\"INSERT into city (Name) VALUES (\'$city\')\")) {
        printf(\"Error: %s\\n\", $mysqli->sqlstate);
    }

    $city = $mysqli->escape_string($city);

    /* this query with escaped $city will work */
    if ($mysqli->query(\"INSERT into myCity (Name) VALUES (\'$city\')\")) {
        printf(\"%d Row inserted.\\n\", $mysqli->affected_rows);
    }

    $mysqli->close();
?>

 

方法二:使用mysqli的prepare语句

当使用准备好的语句和参数化查询时,数据库服务器与任何参数分开发送和解析的这些SQL语句。以这种方式,攻击者不可能注入恶意SQL。

实现代码:

<?php
    // Create a Connection 
    $mysqli = new mysqli(\"server\", \"username\", \"password\", \"db_name\"); 
    $uname = $_POST[\"username\"];
    //check that $stmt creation succeeded 
    // \"s\" means the data  expects a string 
    $stmt = $mysqli->prepare(\"INSERT INTO table (column) VALUES (?)\"); 
    $stmt->bind_param(\"s\", $uname);
    $stmt->execute();
    $stmt->close();
    $mysqli->close();
?>

当通过准备数据库服务器编译的sql语句并指定参数时,我们告诉数据库引擎来过滤参数。之后调用execute语句来将参数与语句进行组合。重要的是要注意,这些参数与编译语句组合而不是sql string。

使用准备语句的另一个好处是,如果在同一个会话中多次执行相同的语句,那么只会对其进行解析和编译一次,从而提高速度。

 

方法三:使用PDO

从PHP 5.1开始,有一个更好的方法。它使用PDO ie。PHP数据对象。它是一个数据库访问层,提供了访问多个数据库的统一方法。它提供了准备语句和处理对象的方法,这将使您更有效率!

 $stmt = $pdo->prepare(\'SELECT * FROM USERS WHERE name = :name\'); 
    $stmt->execute(array(\'name\' => $name)); 
    foreach ($stmt as $row) 
    { 
        /* do something here */
    }
收藏 打印