PHP会话开始不工作


PHP session start not working

未登录时,您可以在浏览器中键入此页面的URL,表单仍会显示。如果没有登录,我不希望HTML显示-只显示必须登录的消息。我在其他页面上使用相同的会话代码,它可以工作-但确实会发出"未定义索引"的通知,这有点烦人。有什么想法吗?

<?php
session_start();
if  ($_SESSION['first_name']&& $_SESSION['username'])
echo "Welcome ".$_SESSION['first_name']."<br><a href='login/logged_out.php'>log    
out</a>";
else
die("You must be logged in. Click <a href='login/login_page.php'>here</a> to log    
in.");
?>
<html>
<head>
</head>
<body>
<form id="1" class="rounded" action="test4.php" method="post"/>
<input type="submit" name="submit"  class="button" value="5" />
<form id="2" class="rounded" action="test4.php" method="post"/>
<input type="submit" name="submit"  class="button" value="6" />
<form id="3" class="rounded" action="test4.php" method="post"/>
<input type="submit" name="submit"  class="button" value="7" />
<form id="4" class="rounded" action="test4.php" method="post"/>
<input type="submit" name="submit"  class="button" value="8" />
<form id="5" class="rounded" action="test4.php" method="post"/>
<input type="submit" name="submit"  class="button" value="9" />
<form id="6" class="rounded" action="test4.php" method="post"/>
<input type="submit" name="submit"  class="button" value="10" />
</form>
</body>
</html>

试试这个:

<?php
session_start();
if(isset($_SESSION['first_name']) && isset($_SESSION['username']) && $_SESSION['firstname']!= ''){
    echo "Welcome ".$_SESSION['first_name']."<br><a href='login/logged_out.php'>logout</a>";
}else{
    die("You must be logged in. Click <a href='login/login_page.php'>here</a> to log in.");
}
?>

它不认为first_name和/或username是会话中的索引

检查是否设置了first_name和/或username

isset($_SESSION['first_name'])
isset($_SESSION['username'])

此外,您可能不想基于这些值验证布尔条件,除非它们本身是布尔值(尽管first_name读起来不像布尔值)。

我不确定"不启动"的问题是什么。可以通过检查isset来防止未定义的索引。您的代码还可以通过使用可变名称和带大括号的括号来改进if/else部分:

session_start();
$isLoggedIn = isset($_SESSION['first_name']) && isset($_SESSION['username']);
if ($isLoggedIn)
{
    echo "Welcome ", htmlspecialchars($_SESSION['first_name']), 
         "<br><a href='login/logged_out.php'>log out</a>";
}
else
{
    echo "You must be logged in. Click <a href='login/login_page.php'>here</a> to log in.";
    return;
}

该变体还使用return而不是die,以将程序流返回给更高的实例。

在处理会话时,您可以添加

print_r($_SESSION);

查看您是否已经设置/取消设置该会话。

您的代码写得很差。我会修改为:

<?php
session_start();
if (empty($_SESSION['first_name']) || empty($_SESSION['username'])) {
    die("You must be logged in. Click <a href='login/login_page.php'>here</a> to log in.");
}
echo "Welcome " . $_SESSION['first_name'];
?>
<br><a href='login/logged_out.php'>logout</a>

除非知道数组索引的存在,否则不应该引用它们。