简体   繁体   English

SQL准备语句(PHP)

[英]SQL prepared statement (PHP)

I am trying to understand how SQL injection works, and how to prevent it. 我试图了解SQL注入如何工作,以及如何防止它。 The HTML login page contains a form, as a table, with a username and password field, and a submit button. HTML登录页面包含一个表格,一个表格,一个用户名和密码字段,以及一个提交按钮。 The PHP code, used with a mySQL database, looks like this: 与mySQL数据库一起使用的PHP代码如下所示:

$conn = mysqli_connect($Host, $User, $Password, $DbName);
if (!$conn) {
 echo "Database connection error.";
 exit;
}
$query = "SELECT user_name, password from visitors where user_name = '".$_POST['user_name']."';";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$user_pass = md5($_POST['pass_word']);
$user_name = $row['user_name'];
if(strcmp($user_pass,$row['password']) != 0) {
 echo "Login failed";
}

To prevent an SQL injection attack, I am trying to implement prepared statements, having had a look at the W3S website, and others. 为了防止SQL注入攻击,我试图实现准备好的语句,看看W3S网站和其他人。 I assume I will need to replace 我想我需要更换

$query="SELECT user_name, password from visitors where user_name='".$_POST['user_name']."';";

with something like this: 用这样的东西:

$stmt = $conn->prepare("SELECT user_name, password from visitors where  user_name= ?");
if ($stmt->execute(array($_GET[‘user_name’]))) {
  while ($row = $stmt->fetch()) {
    $user_name = $row;
  }
} 

I am uncertain about the validity of the amendment. 我不确定修正案的有效性。 Also, in order to test whether the vulnerability of the system has been addressed, how would I be able to gain access to the system via the original, unmodified, code? 此外,为了测试系统的漏洞是否已得到解决,我如何能够通过原始的,未经修改的代码访问系统? I tried: 我试过了:

username: admin
password: ‘ or ‘1’=’1’ (and a number of other options too)

The best way to prevent first, second and third order injections, I'd suggest you to use PDO as well as prepared statements while using the proper charset and disable "Emulated Prepared Statements". 防止一阶,二阶和三阶注入的最佳方法,我建议您在使用正确的字符集时使用PDO以及准备好的语句并禁用“模拟准备语句”。 More information about how an SQL injection works and how PDO can prevent it can be found here . 有关SQL注入如何工作以及PDO如何阻止它的更多信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM