如何防止站点中的SQL注入

时间:2014-01-03 23:13:41

标签: php mysql

我的php文件中有以下代码:

        session_start();
        include "connect.php";
        if (isset($_POST['email']) && isset($_POST['password'])) {
            $email = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['email']));
            $password = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['password'])); 

        function process() {

            include "connect.php";
            if  (isset($_POST['email']) && isset($_POST['password'])) {
                $email = $_POST["email"];
                $password = $_POST["password"];
            }

            mysqli_select_db($conn, "users");
            $sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
            $result = mysqli_query($conn, $sql);
            $count = mysqli_num_rows($result);

            if ($count >= 1) { 
            $_SESSION['id'] = $id;
            $_SESSION['email'] = $email;
            $_SESSION['password'] = $password;
            header('location:index.php');
    } else {
        echo "Email/Password is incorrect";
    }
}
        if ($email != "" or $password != "") {
            if (isset($_POST['submit'])) {
                process();
            } else {
                echo "Error: " . mysql_error();
            }

}
}

我如何在登录页面中阻止sql注入? 我在互联网上搜索过,大多数网站都说我必须使用mysqli_real_escape_string()函数,但是当我再次在我的网站中使用sql注入时,这似乎根本没有改变。 请帮助:)

5 个答案:

答案 0 :(得分:1)

是的,使用PDO并使用try / catch块准备语句。使用prepare时,每个都作为安全参数传递,消除了注射风险。

答案 1 :(得分:0)

使用sql prepare :) http://www.php.net/manual/en/mysqli.prepare.php

据我所知,这可以过滤任何sql注入

答案 2 :(得分:0)

foreach($_POST as $key => $value) $_POST[$key] = mysqli_real_escape_string($value);

最简单的方法,无论如何我建议使用准备语句

答案 3 :(得分:0)

首先, - 为了避免sql注入,你需要过滤任何类型的用户输入。最简单的方法是使用PDO

答案 4 :(得分:0)

您需要使用预准备语句。我认为以下代码片段会让您了解如何使用它。请根据您的要求更改

  /* Create a prepared statement */

  if($stmt = $mysqli -> prepare("SELECT * FROM users WHERE email=? AND password=?")) {

  /* Bind parameters
     s - string, b - blob, i - int, etc */
  $stmt -> bind_param("ss", $email, $password);

  /* Execute it */
  $stmt -> execute();

 $res = $stmt->get_result();
 $row = $res->fetch_assoc();


  $_SESSION['id'] = $row['id'];
  $_SESSION['email'] = $row['email'];
  $_SESSION['password'] = $row['password'];

  header('location:index.php');
  /* Close statement */
  $stmt -> close();
  }

 /* Close connection */
  $mysqli -> close();

文档链接:http://www.php.net/manual/en/mysqli.prepare.php

http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/