我有login.php的这个代码,它连接到数据库,让我进去或不进入。代码本身可以工作,但检查用户是否登录不起作用。 (我不想构建登录表单,有些人只需键入domain.com/welcome.php并进入),无论如何,这是我的login.php代码。当我输入错误的用户名或密码时,它会显示错误,但是当我输入正确的用户名或密码时,它只会将我推回到index.php这是登录表单。
<?php
// Get values from form
$username = $_POST ['username'];
$password = $_POST ['password'];
// Prevent MySQL injection
$username = stripcslashes($username);
$password = stripcslashes($password);
// Connect to database
mysql_connect("domain.com", "sqlusername", "sqlpassword");
mysql_select_db("database");
// Query the database for user
if ( ($username != null || $username != "") && ( $password != null || $password != "" ) ) {
$result = mysql_query("SELECT * FROM members WHERE username = '$username' AND password = '$password'")
or die("Failed to query members " .mysql_error());
if ( mysql_num_rows($result) == 1 ) {
$_SESSION['user'] = $username;
header("location:/welcome.php");
} else {
header("location:/?error=true&msg=2");
}
} else {
// Handle empty entries
header("location:/?error=true&msg=1");
}
?>
这是我的页面,用户名和密码的用户将登录。
<?php
session_start();
var_dump($_SESSION);
if (isset ($_SESSION['user'])){
$username = $_SESSION['user'];
} else {
header("Location: index.php");
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Loged in</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div>
WELCOME <?php $username /?>
</div>
</body>
</html>
提前谢谢。
答案 0 :(得分:2)
您在设置会话值时错过了session_start();
,意味着在login file
。
它必须是这样的
<?php
session_start(); //session starts here
// Get values from form
$username = $_POST ['username'];
$password = $_POST ['password'];
//the other stuff what you wanna do with your username and password
// without starting out session, you cannot set any session values.
?>