【发布时间】:2018-05-16 18:53:22
【问题描述】:
我对所谓的“我认为是 Flash 消息”有疑问。
它应该在输出后从 $_SESSION 数组中清除一个键,但它会在之前清除它。我知道,因为如果我评论 unset() 它可以工作(但当然密钥不会被清除并在刷新时持续存在)简而言之,这将是代码:
if (isset($_SESSION['error'])) {
echo('<p style="color:red; margin:0">'. $_SESSION['error'] .'</p>');
unset($_SESSION['error']);
}
因为它是 echo 语句不起作用。如果注释未设置,则回显有效,但 $_SESSION 键未清除,我需要在输出后清除它。 非常奇怪,我在其他文件中编写了相同的代码,它完美无缺。 这里是谜语爱好者的全部代码。
<?php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])){
unset($_SESSION['username']);
if($_POST['password'] =='umsi' && $_POST['username'] == 'chuck') {
$_SESSION['username'] = $_POST['username'];
$_SESSION['success'] = 'Logged in successfuly';
$_SESSION['password'] = $_POST['password'];
header('Location: app.php');
return;
}
else {
$_SESSION['error'] = 'Login incorrect';
header('Location: log.php');
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="main.css">
<title>Log In</title>
</head>
<body>
<div class="log">
<?php
if (isset($_SESSION['error'])) {
echo('<p style="color:red; margin:0">'. $_SESSION['error'] .'</p>');
unset($_SESSION['error']);
}
?>
<h1>Log in</h1>
<form method="post">
<label for="username">Username</label>
<input type="text" name="username">
<label for="password">Password</label>
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
【问题讨论】:
-
在
header('Location: log.php');之后退出并为exit切换出return。发生的事情是取消设置它的代码,因为你没有退出而被执行。 -
天啊,你的回答让我看到了正确的地方,我错过了标题后的返回!!!
-
np,不要使用 return 使用退出,也总是在
header('Location:...')之后退出,只有浏览器会听,黑客不会听。