我尝试使用php创建登录页面,我希望我的代码检查按下登录按钮后给出的用户名和密码。但即使没有按下登录按钮,代码也会执行。我在线搜索了几十个代码,几乎所有这些代码都以这种方式实现,所以我无法理解这里的错误。这是我的代码:
<HTML>
<HEAD>
<TITLE>Welcome to FoodOrder - Log In or Sign Up</TITLE>
</HEAD>
<BODY background = "foodOrder.png">
<?php
session_start();
$con = mysqli_connect("xxxx", "xxxx", "xxxx", "xxxx");
if(mysqli_connect_errno()){
echo "Failed to connect, please check your username and password: ".mysqli_connect_error();
}
if(isset($_SESSION['user'])!= ""){
header("Location: home.php");
}
if(isset($_POST["login_button"])){
$username = mysqli_real_escape_string($_POST['username']);
$password = mysqli_real_escape_string($_POST['password']);
$sql = "SELECT password from user where username = '$username'";
$res = mysqli_query($con,$sql);
$row = mysqli_fetch_array($res);
if($row['password'] == md5($password)){
$_SESSION['user'] = $username;
header("Location : home.php");
} else {
?> <script>alert('wrong username or password');</script> <?php
}
}
?>
<center>
<div id ="login form">
<form method = "POST">
<table align = "center" width = "25%" border = "0">
<tr>
<td><input type = "text" name = "username" placeholder = "your_username_here" required></td>
</tr>
<tr>
<td><input type = "text" name = "password" placeholder = "your_password_here"></td>
</tr>
<tr>
<td><input type = "submit" name = "login_button" value = "Log In" /></td>
</tr>
<tr>
<td><a href = "register.php">Sign Up</a></td>
</tr>
</table>
</form>
</div>
</center>
</BODY>
</HTML>
答案 0 :(得分:0)
删除md5
一次,检查您的代码。 $_SESSION
VARIABLE无法正常工作。
也尝试替换此
if(isset($_SESSION['user'])!= ""){
header("Location: home.php");
}
用这个
if(!$_SESSION['user']){
header("Location: home.php");
}