我在本地服務器上建立了一個身份驗證系統,以使用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