我在本地服务器上建立了一个身份验证系统,以使用PHP和MYSQL测试运行某些脚本以供我个人使用。我跑了下面的代码,选择从“用户”表中的“用户名”和“密码”列,但我基普输入正确的凭据后收到此错误:无法选择用户名和密码用户表(MySql)的列
Invalid username/password combination
下面是脚本:
<?php // authentication.php
require_once 'login.php';
$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])) {
$un_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($connection, $_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username='$un_temp' AND password='$pw_temp'";
$result = $connection->query($query);
if (!$result) die($connection->error);
else if ($result->num_rows) {
$row = $result->fetch_array(MYSQLI_NUM);
$result->close();
if (password_verify($pw_temp == $row[3])) {
echo "$row[0] $row[1] : Hi $row[0], you are now logged in as '$row[2]'";
}
}
else die("Invalid username/password combination");
} else {
header('WWW-Authenticate: Basic realm="Restricted Section"');
header('HTTP/1.0 401 Unauthorized');
die("Pleaser enter your username and password");
}
$connection->close();
function mysql_entities_fix_string($connection, $string) {
return htmlentities(mysql_fix_string($connection, $string));
}
function mysql_fix_string($connection, $string) {
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return $connection->real_escape_string($string);
}
?>
** WARNING **:当使用'mysqli'你应该使用[参数化查询( http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)和['bind_param'](http://php.net/manual/en/mysqli-stmt.bind-param.php )将用户数据添加到您的查询。 **不要**使用手动转义和字符串插值或串联来实现此目的,因为您将创建严重的[SQL注入漏洞](http://bobby-tables.com/)。意外地未经转义的数据是一个严重的风险。使用绑定参数不那么冗长,并且更容易检查以检查您是否正确地进行了操作。 – tadman
如果你使用'mysql_entities_fix_string',那么你在这里遇到了一些严重的问题,那大概是手动滚动的函数是不够的。 – tadman
**警告**:编写您自己的访问控制层并不容易,并且有很多机会使其严重错误。请不要在[Laravel](http://laravel.com/)等任何现代开发框架(http://codegeekz.com/best-php-frameworks-for-developers/)上编写自己的认证系统,内置了强大的[认证系统](https://laravel.com/docs/5.4/authentication)。绝对不会遵循[推荐的安全最佳实践](http://www.phptherightway.com/#security),并且从不使用无用的弱散列(如SHA1或MD5 **)存储密码。 – tadman