简体   繁体   中英

php set session with cookies

$_SESSION['user_id'] = $login;  
setcookie('user_id', '$login' , time()+86000);
header('Location: userindex.php');

function logged_in() {
return (isset($_SESSION['user_id']) || isset($_COOKIE['user_id']) ? true : false;
}

I have SESSION but I wonna include COOKIE too but I don't know how to restart SESSION with COOKIE. I don't have a idea how I can get that. I create COOKIE but can't logout and have problem with SESSION somebody can help me to fix my problem???? And in every page on top I have logged_in function for check if user is logged in or not I wonna these logged_in function to check if user has cookie to auto login to user cookie. I think it is in logged_in function must get write some code and...

I will note that this is not secure, as any one can create the cookie, using something like firebug.

@session_start();

function logged_in() {
    if(!isset($_SESSION['user_id']) && isset($_COOKIE['user_id'])) {
        $_SESSION['user_id'] = $_COOKIE['user_id'];
    }
    return isset($_SESSION['user_id']);
}

function logout() {
    unset($_SESSION['user_id']);
    setcookie("user_id", "", time() - 3600);
    header("Location: http://".$_SERVER['HTTP_HOST']);
    exit;
}

Edit: Added logout() - will remove both session and cookie 'user_id', then redirect to homepage

First: you should set it with:

setcookie('user_id', $login , time()+86000);

So $login without quotes. And also maybe set path variable if this cookie should be seen in different pages.

Removing cookie is done with setting negative time value:

setcookie('user_id', '' , time()-86000);
session_start();

function logged_in() {

    if(!isset($_SESSION['user_id']) && isset($_COOKIE['user_id'])) {

        $_SESSION['user_id'] = $_COOKIE['user_id'];
    }

    return (isset($_SESSION['user_id'])) && isset($_COOKIE['user_id'])));
}

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