设计用户成员资格的另一种尝试。必须成功登录,才能在数据库中查找数据。但是在我的索引文件中,登录后,应检查我是否已登录并显示指向我帐户的链接,而不是注册和登录。这是代码:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '<a href="member_profile.php?id=' . $userid . '">' . $username . '</a> •
<a href="member_account.php">Account</a> •
<a href="logout.php">Log Out</a>';
} else {
$toplinks = '<a href="join_form.php">Register</a> • <a href="login.php">Login</a>';
}
?>
这是登录表单代码,我认为问题是因为它没有存储我的会话ID:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br /><a href="login.php">Click here</a> to go back to the login page.';
exit();
}
}// close if post
?>
我再次关注某人的教程,并尝试将其实施到我的网站,如果有效,这将是完美的。请注意登录后没有设置$ toplinks的原因。
答案 0 :(得分:3)
我认为问题是,您必须在要使用会话的每个文件中包含session_start()
。否则它在文件中工作就像普通数组但不是全局数据。在你的表格中,我看不到你开始你的会话。
编辑:仅当您有2个文件时才需要此功能。如果您只有一个文件并且包含另一个页面,那么当您在顶部包含一次时它就会正常工作。
答案 1 :(得分:1)
如果要注销,则应创建注销文件,并包含
session_destroy();
可能通过执行以下操作添加一个href来获取重定向链接:
header('location:index.php'); // will return you to index as soon as you logout.