我可以知道为什么它没有重定向到我一直在寻找的页面,我有一些问题,如果我输入正确的用户名,它仍然显示我输入了错误的用户名/密码。这是我的代码片段。有人可以帮帮我吗?谢谢。还有人如何开会?
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `user` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysqli_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
header("Location: home.php"); // Redirect user to homeA.php
}else{
echo "<center><div class='form'><br><br><h1>Username/password is incorrect.</h1><br/>Click here to <a href='main.php'>Try Again</a></div></center>";
}
}
else{
?>
答案 0 :(得分:1)
首先,请使用预准备语句而不是字符串连接来构造sql语句。解决这个问题的一个简单方法是使用PDO。其次,永远不会使用MD5哈希密码。 PHP中的密码哈希是使用password_hash()
和password_verify()
函数完成的。
下面是一个使用前面提到的方法登录页面如何工作的示例。
// Create a new PDO object using host (might be 127.0.0.1), dbname (your database name), user (your database username) and pass (your database password)
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
if (isset($_POST['username'])) {
$stmt = $dbo->prepare('SELECT * FROM user WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
if ($stmt->execute()) {
$row = $stmt->fetch();
if (password_verify($_POST['password'], $row['password'])) {
// User password matched. Log them in
} else {
// User password didn't match
}
} else {
// There was a problem executing query
}
}
创建用户时,您还需要使用password_hash()
哈希密码。
password_hash($password, PASSWORD_DEFAULT)