-2
我有一段代碼檢查以確保您嘗試登錄的帳戶實際存在並位於數據庫中。但是,當我用測試帳戶測試它時,當我嘗試登錄時(即使它正確並在數據庫上),它說它不是。html php mysql登錄正確,但顯示它的錯誤
// login
if (isset($_POST[login])){
$username=mysqli_real_escape_string($db,$_POST['username']);
$password=mysqli_real_escape_string($db,$_POST['password']);
// ensure that form is filled right
if (empty($username)){
array_push($errors,"include username");
}
if (empty($password)){
array_push($errors,"include password");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($db,$query);
if (mysqli_num_rows($result) == 1){
$_SESSION['username'] = $username;
$_SESSION['success'] = "Hi you are now in";
header('location: index.php');
} else {
array_push($errors,"username or password are wrong");
//header('location: login.php');
}
}
}
有人可以告訴我它有什麼問題嗎? 謝謝。
編輯:
它通過註冊頁面中插入數據:
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'wildeart_am','test', 'wildeart_register');
// if the register button is clicked
if (isset($_POST[register])) {
$username=mysqli_real_escape_string($db,$_POST['username']);
$email=mysqli_real_escape_string($db,$_POST['email']);
$password=mysqli_real_escape_string($db,$_POST['password']);
$confirmpassword=mysqli_real_escape_string($db,$_POST['cpassword']);
// ensure that form is filled right
if (empty($username)){
array_push($errors,"include username");
}
if (empty($email)){
array_push($errors,"include email");
}
if (empty($password)){
array_push($errors,"include password");
}
if($password != $confirmpassword){
array_push($errors,"The two passwords must match");
}
// register
if(count($errors) == 0){
$password = md5($password);
$sql = "INSERT INTO users (username, email, password)
VALUES ('$username', '$email','$password')";
mysqli_query($db, $sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "Hi you are now in";
header('location: index.php');
}
}
編輯2:
要嘗試和MD5解決密碼哈希密碼哈希我所做的:
if(count($errors) == 0) {
$password = password_hash($password, PASSWORD_BCRYPT, $options);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_row($result);
$verify=password_verify($_POST['password'],$row[1]);
if($verify){
$_SESSION['username'] = $username;
$_SESSION['success'] = "Hi you are now in";
header('location: index.php');
}else{
array_push($errors,"username or password are wrong");
//header('location: login.php');
}
但它似乎仍然沒有工作。
不應該'$ _ POST [登錄]'是'$ _ POST [「登錄」]'呢? – Mihailo
**不要存儲由md5散列的密碼!** PHP提供['password_hash()'](https://php.net/manual/en/function.password-hash.php)和['password_verify()'] (https://php.net/manual/en/function.password-verify.php)請使用它們。如果您使用的是5.5以前的PHP版本[這裏有一個兼容包](https://github.com/ircmaxell/password_compat)。確保你[**不要轉義密碼**](https://stackoverflow.com/q/36628418/5914775)或在哈希之前使用其他任何清理機制。這樣做會更改密碼並導致不必要的附加編碼。 –
@Mihailo PHP實際上會自行解決它,但會發出警告。 – Qirel