我正在尝试将会话变量存储在登录页面中,然后将其传递到成员页面,但由于某种原因,当您转到成员页面时,会话变量不会存储。
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
?>
然后是一堆html。然后下一个PHP代码是......
<?php
$form = "<form action='login.php' method='post'>
<table>
<tr>
<td><input type='text' name='user' /></td>
</tr>
<tr>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td><input type='submit' name='loginbtn' value='Login' /></td>
</tr>
</table>
</form>";
if ($_POST['loginbtn']) {
$user = $_POST['user'];
$password = $_POST['password'];
if ($user) {
if ($password){
require("connect.php");
$password = md5(md5("kjfiufj".$password."GSA54"));
//make sure login info is correct
$query = mysql_query("SELECT * FROM users WHERE username='$user'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
$dbid = $row['id'];
$dbuser = $row['username'];
$dbpassword = $row['password'];
$dbactive = $row['active'];
if ($password == $dbpassword) {
if ($dbactive == 1) {
//set session info
$_SESSION['userid'] = $dbid;
$_SESSION['username'] = $username;
echo "logged in as <strong>$dbuser</strong>. <a href='member.php'>Click here</a> to go to the member page.";
}
else
echo "User not active";
}
else
echo "Wrong password.";
}
else
echo "The username you entered was not found";
mysql_close();
}
else
echo "What's the password brah?";
}
else
echo "What's the user name brah?";
}
else
echo $form;
?>
会员页面的代码是
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
?>
<?php
if ($username && $userid) {
echo "Welcome <strong>$username</strong>,<a href='logout.php'>Logout</a>.";
}
else
echo "Please login to acces this page <a href='login.php'>Login here</a>";
?>
答案 0 :(得分:2)
您是否在登录页面中呼叫session_start()
?
如果尚未将session_start()
运行时配置选项设置为session.auto_start
,则必须在将要访问会话变量的每个页面中调用true
。
的修改
实际上,您的$_SESSION['userid']
可能不是空的,因为您实际上已将定义的变量指定为$_SESSION['userid'] = $dbid;
但是,您要通过为$_SESSION['username']
分配$username
的值来创建$_SESSION['username'] = $username;
,这似乎是未定义的。
也许
$_SESSION['username'] = $dbuser;
应该是
{{1}}
答案 1 :(得分:0)
检查变量实际上是否包含某些内容
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
?>
<?php
if (strlen($username) >0 && strlen($userid)>0) {
echo "Welcome <strong>$username</strong>,<a href='logout.php'>Logout</a>.";
}
或检查会话变量是否已设置
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
?>
<?php
if (isset($_SESSION['username']) && isset($_SESSION['userid'])) {
echo "Welcome <strong>$username</strong>,<a href='logout.php'>Logout</a>.";
}