简体   繁体   中英

Cookies won't set, session works

I'm sorry for the small amount of information, but there is not much else I can give you. The problem is, when trying to extend my login function to add an option for staying logged in, the cookies won't set. The session itself works (so there are no blank characters or something). I get no error messages, the cookie just doesn't set (tested with opera/firefox). After being puzzled for over an hour, i decided to ask it here. Below is the login function. Further down you will find how it's called. Don't worry about the password in the cookie, it's hashed. I tested if the code is in fact executed (placed an echo 'abc' before setcookie) which is the case.

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
}

}

This is how the above function is called.

<?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;
}

Thanks a lot.

Your cookie won't set because you're outputting HTML headers before the log in / cookie setting functionality happens.

You can't pass any headers to the browser prior to creating the cookie.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM