首先,对于措辞不佳的标题问题感到抱歉。我正在编写一个小程序,其中login()函数在被调用时获取用户名'和'用户级别'来自数据库。如果条目有效,则将用户带到注销页面。它所做的只是欢迎用户并提示他们注销。但是,当我使用以下代码时,它不显示用户信息:
... logoutForm.inc.html
<!DOCTYPE HTML>
<html>
<head>
<title>Welcome</title>
<link rel="icon" type="image/png" href="http://upload.wikimedia.org/wikipedia/commons/a/ac/Farm-Fresh_key.png">
<meta charset="utf-8">
</head>
<body>
<div id = "wrapper">
<div id="masthead">
<h2>Welcome, <?php echo $userName; ?>!</h2>
<h3>Your current user level is <?php echo $userLevel; ?></h3>
<form action method="post" name="logoutForm">
<p>
<input type="submit" name="logout" value="Log Out" />
</p>
</form>
</div>
</div>
</body>
</html>
...的functions.php
<?php
function login($userName)
{
if (empty($userName)){
echo '<h2>You forgot to enter something</h2>
<meta http-equiv="refresh" content="2; url=login.php" />';
}
else
{
$conn = new PDO("mysql:host=localhost:3307;dbname=users", "root", "");
$result = $conn->prepare("SELECT * FROM user_list WHERE email = :username");
$result->bindParam(':username', $userName);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
if($row > 0) {
if ($row['userLevel'] == 'A')
{
$userLevel = 'Admin';
}
elseif ($row['userLevel'] == 'M')
{
$userLevel = 'Member';
}
header("Location: includes/logoutForm.inc.html");
}
else
{
echo '<h2>That entry is INVALID</h2>
<meta http-equiv="refresh" content="2; url=login.php" />';
}
}
}
function logout($userName)
{
session_start();
echo '<title>Logout</title>
<link rel="icon" type="image/png" href="http://upload.wikimedia.org/wikipedia/commons/a/ac/Farm-Fresh_key.png">
<meta charset="utf-8">';
$_SESSION['username'] = array();
session_destroy();
$name = session_name(); $expire = strtotime('-1 year'); $params = session_get_cookie_params(); $path = $params['path']; $domain = $params['domain']; $secure = $params['secure']; $httponly = $params['httponly'];
setcookie($name, '', $expire, $path, $domain, $secure, $httponly);
die('<h3>You have successfully logged out</h3>
<meta http-equiv="refresh" content="2; url=login.php" />');
}
更不用说logout()函数完全被搞砸了。一次解决这个问题。感谢您的关注,如果可以,请提供帮助。
答案 0 :(得分:1)
如果您希望登录持续存在,则需要将信息存储在会话中(如果您需要将会话保存的时间比浏览会话长,则会话可以存储在数据库中):
if($row > 0) {
// start the session, you might want to do that at the top of your script
session_start();
if ($row['userLevel'] == 'A')
{
$_SESSION['userLevel'] = 'Admin';
}
elseif ($row['userLevel'] == 'M')
{
$_SESSION['userLevel'] = 'Member';
}
现在,您可以在已登录的页面中启动会话,并检查是否已设置变量以及确切的用户权限。
注意:请勿使用查询字符串来传递这些变量,如评论中所述。这将允许任何人只是通过更改查询字符串假装使用他们想要的权限登录。会话存储在服务器端,因此访问者无法对其进行操作。