[英]Username and Password trouble in PHP
我正在嘗試使用PHP創建登錄表單,但無法登錄。 我得到的密碼/用戶名不正確。 我已經三重檢查了數據庫中的憑據,它們是正確的。 請幫忙
這是代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysqli_real_escape_string($connection,$username);
$password = stripslashes($password);
$password = mysqli_real_escape_string($connection,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `backuser` WHERE username='".$username."' and password='".md5($password)."'";
$result = $connection->query($query) or die(mysqli_error());
$rows = mysqli_num_rows($result);
if($rows==0){
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect user to index.php
}else{
echo " <div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>
您的邏輯有誤。 將if($rows==0)
更改為if($rows!=0)
。 如果用戶在DB中,則應至少返回1條記錄,並且mysqli_num_rows()
應返回一個數字>= 1
。
薩拉斯瓦蒂(Sarasvati)的答案似乎可以解決您眼前的問題,但是我也建議:
使用內置的PHP Password hashing函數(PHP 5.5+和5.3)來哈希密碼。 MD5在密碼學上不安全,不建議用於密碼存儲或檢查。
如果你是新的PHP是非常非常值得你花時間探索使用預處理語句與您的代碼。 這樣可以將code
與user input
分開,從而大大降低了SQL注入和數據庫破壞的風險。
當您有一個重定向的header
,應立即在此標頭后面加上一個exit
語句,因為其余的PHP代碼仍將在標頭跟隨之前運行。
$_SESSION['username'] = $username; header("Location: index.php"); // Redirect user to index.php exit;
不要在密碼字段上使用諸如stripslashes()
類的文本編輯功能,如果某人的密碼中有斜杠,它將被剝奪並且他們將無法登錄。密碼應為任何字符,而不僅僅是z或0- 9等
對於MySQLi_
[procedural]錯誤報告,您需要提供連接詳細信息:
die(mysqli_error($connection));
否則,報告將不會給您任何東西。
PHP session_start()
應該在任何內容輸出到瀏覽器之前,因此它必須在PHP頁面的頂部。 ( 感謝Nitin,我本來想念這個的 )。
問題是我沒有在數據庫中分配足夠的存儲(字符長度)來存儲哈希值。 我將長度值調整為30,它就像一個吊飾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.