Cookies不会设置,会话有效
问题描述:
对于少量的信息我很遗憾,但是我可以给你的东西并不多。问题是,当试图扩展我的登录功能以添加一个保持登录的选项时,Cookie不会设置。会议本身的作品(所以没有空白字符或东西)。我没有收到任何错误消息,该cookie只是没有设置(使用opera/firefox进行测试)。在困惑了一个多小时之后,我决定在这里问问。以下是登录功能。再往下看,你会发现它是如何被调用的。不要担心cookie中的密码,它会被散列。我测试了代码是否被实际执行(在setcookie之前放置了一个echo'abc')。Cookies不会设置,会话有效
public function login($password,$stayloggedin) {
if (is_null($this->id)) trigger_error ("user::login(): Attempt to login an user object that does not have its ID property set.", E_USER_ERROR);
if ($this->compare_password($password))
{
if ($stayloggedin)
{
setcookie("userid", $this->id, time()+3600);
setcookie("userid", $this->password, time()+3600);
}
session_start();
$_SESSION['user_id'] = $this->id;
$_SESSION['user_name'] = $this->name;
$_SESSION['user_nummer'] = $this->user_nummer;
return true;
}
else
{
return false; //wrong password
}
}
这是如何调用上述函数的。
<?php
header('Content-type: text/html; charset=UTF-8');
require_once 'required_script.php';
if (isset($_GET['login']))
{
require_once CLASS_PATH.'user.class.php';
$user_logging_in=new user();
$user_logging_in->load_from_name($_POST['user_name']);
if (isset($user_logging_in->id))
{
if ($user_logging_in->login($_POST['user_pass'],$_POST['remember_me']=='true'))
{
echo '1';
}
else
{
echo '0';
}
}
else
{
echo '2';
}
die;
}
非常感谢。
答
您的cookie不会设置,因为您在登录/ cookie设置功能发生之前正在输出HTML标头。
在创建cookie之前,您无法将任何标头传递给浏览器。
我会尝试使用下一个两个参数的'setcookie' – thewebguy
谢谢,这实际上解决了这个问题。你能解释一下为什么?并请将其重新发布为答案,以便我可以给您适当的信用。 – Boelensman1
我现在明白了为什么。登录发生在/后端,cookie检入正常目录。所以这个cookie只被设置为/后端。非常感谢:) – Boelensman1