Praveen Pachauri February 2016

asking about the cookie after logout

I'm trying to access a cookie's value (using $_COOKIE) immediately after calling the setcookie() function in PHP. When I do so, $_COOKIE[$cookiename] isn't set after login. Why?

if(isset($_SESSION)){
    $_SESSION['email']=$username;
    $_SESSION['id']=$query['id'];
    $_SESSION['name']=$query['name'];
    $_COOKIE[$cookiename]=$query['name'];


    $cookiename="user";
    $cookie_value = "John Doe";
    setcookie($cookiename,$cookie_value, time() + (86400 * 30),"/");
    if (!$session->Check()){
        echo $cookiename ;
    }else {
        echo $_COOKIE[$cookiename];
    }

Answers


codeHeart February 2016

  1. This is because when you call setcookie() you are attaching the cookie to the current response(when the current request completes).

  2. $_COOKIE will have a value when a request is made with the cookie header already set i.e cookie is sent to the server.

So, when only #1 happens you don't have anything in $_COOKIE, but once #2 happens you will have a value in $_COOKIE

EDIT: Almost everything you need is mentioned in the manual http://php.net/manual/en/function.setcookie.php

setcookie() defines a cookie to be sent along with the rest of the HTTP headers Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.

Post Status

Asked in February 2016
Viewed 3,609 times
Voted 8
Answered 1 times

Search




Leave an answer