mysqli_real_escape_string 安全吗?

2021-12-25 00:00:00 php mysqli sql-injection

我是 PHP 新手,我意识到我的数据库连接,使用 php 表单(带有用户和传递文本输入)是完全不安全的:

I´m new in PHP and I´ve realised that my database connection, using a php form (with user and pass text inputs) was totally unsafe:

这是有效的,但不安全:

This was working, but was unsafe:

<?php
$link=mysqli_connect('localhost','xx','xx','xx');
$sql='  SELECT * FROM usuarios 
        WHERE username="'.$_POST['usuario'].'" 
        AND pass="'.$_POST['usuario'].'"
     ';
$rs=mysqli_query($link,$sql);
mysqli_close($link);
?>

所以,我已经阅读了 mysqli_real_escape_string,并决定尝试一下:

So, I´ve read about mysqli_real_escape_string, and decided to try it out:

<?php    
$link=mysqli_connect('localhost','xx','xx','xx');
$usuario=mysqli_real_escape_string($link, $_POST["usuario"]);
$clave=mysqli_real_escape_string($link, $_POST["clave"]);
$sql='  SELECT * FROM usuarios 
        WHERE username="'.$usuario.'" 
        AND pass="'.$clave.'"
     ';
$rs=mysqli_query($link,$sql);
mysqli_close($link);
?>

这是正确的吗?这是如何使用 mysqli_real_escape_string 的好例子吗?

Is this correct? Is this a good example of how to use mysqli_real_escape_string?

推荐答案

这是正确的吗?

是的.

这是如何使用 mysqli_real_escape_string 的好例子吗?

Is this a good example of how to use mysqli_real_escape_string?

如果曾经使用过,这个函数必须被封装到一些内部处理中,并且永远不必从应用程序代码中直接调用.必须使用占位符来表示查询中的数据:

$sql='SELECT * FROM usuarios WHERE username=? AND pass=?';

然后,在处理占位符标记时,此功能可以被应用(如果适用)但不是单独应用,而是沿着所有格式规则应用.

And then, upon processing placeholder marks, this function may be applied (if applicable) but not by itself but along ALL the formatting rules.

相关文章