Search code examples
phpcookiesbrowserkohana

Are newly created cookies not available until a subsequent page load?


When I first create a cookie I don't seem to be able to grab that same cookie until a subsequent page load. It's as if the cookie doesn't exist to the browser until the page is requested a second time.

I'm using the Kohana PHP framework:

Cookie::set('new_cookie', 'I am a cookie');
$cookie = Cookie::get('new_cookie');
//$cookie is NULL the first time this code is run. If I hit the page again
and then call Cookie:get('new_cookie'), the cookie's value is read just fine.

So, I'm led to believe that this is normal behavior and that I probably don't understand how cookies work. Can anyone clarify this for me?


Solution

  • Cookies are set in HTTP headers, so when the server returns the page. When you reload the page, your browser will send them back to the server.

    So, it is perfectly normal they are "visible" just after a new request.

    Here is an example response from the server:

    HTTP/1.1 200 OK
    Content-type: text/html
    Set-Cookie: name=value
    Set-Cookie: name2=value2; Expires=Wed, 09-Jun-2021 10:18:14 GMT
    
    (content of page)
    

    When you reload the page, your browser sends this:

    GET / HTTP/1.1
    Host: www.example.org
    Cookie: name=value; name2=value2
    Accept: */*
    

    This is why the server can see them only after a new request by the browser.