我试图通过密码保护来保护页面。我使用下面的代码,但它不起作用。
home.php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
if(!isset($_SESSION['user_name'])) { header('Location: login.php'); die('<a href="login.php">Login first!</a>'); }
login.php的相关部分
<?php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
答案 0 :(得分:3)
试试这个
session_start();
if(!isset($_SESSION['user_name']))
{
header('Location: login.php');
exit;
}
$username = $_SESSION["user_name"];
$password = $_SESSION["password"]; *//EDITED*
编辑:
登录login.php
<?php
session_start();
if(isset($_SESSION['user_name']))
{
header('Location: home.php');
exit;
}
?>
<input type = 'text' name = 'login' />
<input type = 'password' name = 'password' />
<input type = 'submit' name = 'submit' />
编辑2:
成功登录后写下
$_SESSION["user_name"] = $_POST["user_name"];
$_SESSION["password"] = $_POST["password"];
这将在会话变量中设置post
所以它看起来像这样
现在,当您检查if(isset($_SESSION['user_name']))
时,它将返回true并重定向到主页
答案 1 :(得分:2)
因为你没有真正完全问过这个问题,所以只是一个猜测。但请尝试替换:
$username = $_SESSION["user_name"];
与
$username = $_POST["user_name"];
答案 2 :(得分:1)
您似乎正在复制一个空用户名,然后将空$ username的值更改为您的会话数组。
您希望尽可能少地修改会话的信息。
所以在您的更新页面中:
<?php
session_start();
// is the line below necessary on this page?
if ( $_POST['user_name'] != "" ) {
$_SESSION['user_name'] = $_POST['user_name'];
}
if ( ( trim($_SESSION['user_name']) != "" ) ) {
echo $_SESSION['user_name'];
} else {
header("Location: login.php");
die();
}
更新:删除了评论专栏
答案 3 :(得分:1)
您正在使用的login.php
和home.php
:
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
根本没有意义,只有在满足登录条件(成功登录)时才设置会话变量,而在其他任何地方都没有。在其他地方,您只需检查它是否存在/已设置。
由于您尚未发布处理登录的部分,因此很难说是否存在其他错误。