我正在为我正在为网站的“成员”部分工作的网站创建一个非常基本的用户登录界面。我正在使用 $_SESSION 变量来存储信息。['access'] 存储一个关于用户是否被允许访问的布尔值,如果用户名/密码不匹配,['invalid'] 为真(用于错误处理),如果 ['no_attempt'] 为真用户尝试在未登录的情况下访问受限页面,并且 ['uri'] 存储他们尝试在未登录的情况下访问的页面的 URI。
到目前为止,按照我对页面的编码方式,一切正常,除了当 ['no_attempt'] 为真时永远不会显示错误消息。以下是我网页的摘录:
登录.php
session_start();
if(md5($_POST['username']) === '[username hash]' && md5($_POST['password']) === '[password hash]') {
// allow access to members pages
$_SESSION['login']['allow'] = true;
// clear error messages
$_SESSION['login']['invalid'] = false;
$_SESSION['login']['no_attempt'] = false;
// if a url hasn't been stored for redirect, direct to the members home page
if (!isset($_SESSION['login']['redirect']) || empty($_SESSION['login']['redirect'])) $_SESSION['login']['redirect'] = '/members';
header("Location: {$_SESSION['login']['redirect']}");
}
else {
$_SESSION['login']['invalid'] = true;
header('Location: /');
}
每个受限页面的开头都以以下代码开头:
session_start();
if($_SESSION['login']['allow'] != true) {
$_SESSION['login']['redirect'] = $_SERVER['REQUEST_URI'];
$_SESSION['login']['no_attempt'] = true;
header('Location: /');
}
require ('../assets/includes/site-header.php');
site-header.php
这个页面在我网站每个页面的开头被调用。它有标题、导航栏和类似的东西。下面只是侧边栏的会员登录部分。
if(isset($_SESSION['login']['allow']) && $_SESSION['login']['allow'] == true) {
echo "<li><a href=\"/members\" id=\"members\">Members</a></li>\n";
}
else {
echo "<li>\n";
echo "<div class=\"expandable\">Members <span class=\"show-hide\">+</span></div>\n";
echo "<div class=\"nav-details\">\n";
if (isset($_SESSION['login']['invalid']) && $_SESSION['login']['invalid'] == true) {
echo "<div id=\"login-error\">The username or password you<br />entered was incorrect.</div>\n";
}
elseif (isset($_SESSION['login']['no_attempt']) && $_SESSION['login']['no_attempt'] == true) {
echo "<div id=\"login-error\">You must login before<br />accessing that page.</div>\n";
}
echo "<form method=\"post\" action=\"/members/login.php\" id=\"login-form\">\n";
echo "Username:<br />\n";
echo "<input type=\"text\" name=\"username\" /><br /><br />\n";
echo "Password:<br />\n";
echo "<input type=\"password\" name=\"password\" /><br /><br />\n";
echo "<input type=\"submit\" value=\"Login\" id=\"login-button\" />\n";
echo "</form>\n";
echo "</div>\n";
echo "</li>\n";
}
$_SESSION['login']['invalid'] = false;
$_SESSION['login']['no_attempt'] = false;