我在尝试创建一个简单的登录系统时遇到问题。这是我的设置:
索引.php
<?php if(!isset($_SESSION['username'])){
session_start();
//present login form with action=login.php
} else {
//display actual page
}
?>
登录.php
<?php
if(!empty($_SESSION['username'])){
echo $_SESSION['username'];
} else {
$username=$_POST['username'];
$password=sha1($_POST['password']);
$link=mysqli_connect("localhost","root","password","database",3306,"/tmp/mysql.sock");
$query="SELECT * FROM login WHERE `name`='".$username."' AND `passwordhash`='".$password."' LIMIT 1";
$result=mysqli_query($link,$query);
if(mysqli_num_rows($result)==1){
session_start();
$_SESSION['username']=$username;
$row=mysqli_fetch_assoc($result);
$_SESSION['firstname']=$row['firstname'];
$_SESSION['lastname']=$row['lastname'];
echo "Username: ". $_SESSION['username']." Name: ".$_SESSION['firstname']." ".$_SESSION['lastname']; //this is just here as POC. If I redirect to index.php (using header()), it shows the login form (claims $_SESSION['username'] is unset).
}
}
?>
一旦我登录,它会在 login.php 上显示我的用户名和名字和姓氏(不是数据库问题)。但是如果我重定向到 index.php,它会立即显示登录表单。有什么问题?编辑:即使在将 session_start() 添加到 login.php 之后,也会产生相同的结果。