By heapzero

2010-07-12 16:13:50 8 Comments

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

Note, however, that $_COOKIE['uname'] is set as expected upon the next execution of the script, such as after a page refresh.

setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . $_COOKIE['uname'];


@Sebastiaan Koopman 2019-06-04 13:33:57

I had a similar problem where i used a function from a included file and solved it with a function that both returns the value of the cookie and sets the cookie.

function setCookie($input) {
  setcookie('uname', $input, time() + 60 * 30);
  return $input;

if(!isset($_COOKIE['uname'])) {
    $uname  = setCookie($whatever);
} else {
    $uname = $_COOKIE['uname'];

echo "Cookie value: " . $uname;

@Joshua 2017-06-01 19:37:07

You have to set the cookie variable by yourself if you need it immediately, by the time you load another page the real cookie would have been set as a result of the setcookie method.

setcookie('name', $value, time()+60*30);
$_COOKIE ['name'] = $value;

@witrin 2015-12-25 19:07:06

If you want to access a cookie's value immediately after calling the setcookie() you can't use $_COOKIE. The reason for this is in the nature of the protocol (see When you use setcookie() it defines a Cookie to be sent along with the rest of the HTTP headers to the client (see But $_COOKIE on the other hand contains variables passed to the current script via HTTP Cookies from the client (

When you change $_COOKIE after calling setcookie() - like some answers here recommend - it doesn't contain only the Cookies from the client any more. This could interferer with assumptions made in third party code used in your application and may result in unwanted site effects. So in general it's not good practice and it's only an option when the calls of setcookie() are part of your own code.

A clean and transparent way to get a value set with setcookie() within the same request is to use headers_list() (see

function getcookie($name) {
    $cookies = [];
    $headers = headers_list();
    // see
    foreach($headers as $header) {
        if (strpos($header, 'Set-Cookie: ') === 0) {
            $value = str_replace('&', urlencode('&'), substr($header, 12));
            parse_str(current(explode(';', $value, 1)), $pair);
            $cookies = array_merge_recursive($cookies, $pair);
    return $cookies[$name];
// [...]
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . getcookie('uname');

But notice this won't work in PHP CLI (e.g. PHPUnit). In such a case you could use third party extensions like XDebug (see

@Michael 2016-09-20 15:41:17

Only one real solution here. Clean, without modifications of 3rd party code that could contain setcookie.

@ChrisP777 2018-03-19 17:28:33

I am not sure why the op voted for the other solution, but this is the correct solution that actually helped me.

@Fakirchand Patidar 2015-11-18 10:09:25

We can do this using AJAX calling.

If we want to create cookies on button click so first create a AJAX call for creating cookies then the success of first AJAX calling we can call another AJAX for getting the cookies.

    function saveCookie() {
            var base_url = $('#base_url').val();
            var url = base_url + '/index/cookie';
                'url': url,
                'type': 'POST',
                'success': function (data) {
                    if (data) {
                        var url = base_url + '/index/get_cookie';
                            'url': url,
                            'type': 'POST',
                            'success': function (response) {
                                var container = $('#show');
                                if (response) {

    <button type="button" onclick="saveCookie()">Save Cookie</button>
    <div id="show"></div>

@Máxima Alekz 2019-01-23 19:29:33

Know that even when intentions are good, OP requires a PHP only answer. :) Maybe that's why you have downvotes, I did not downvoted you.

@Dhruv Thakkar 2019-03-29 10:00:15

upvoted because this is also a one approach that should be considered!

@virtualLast 2015-05-20 14:20:54

I set a constant at the same time the cookie was created

define('CONSTANT', true);
return setcookie('cookiename', 'cookie value goes here', time() + 60 * 60 * 24 * 30, '/');

I can then immediately do something by:

if(isset($_COOKIE['cookiename']) || $_COOKIE['cookiename'] || defined('CONSTANT') && CONSTANT)

@Robert Rocha 2015-02-20 00:51:46

Your script's setcookie() function runs when the web browser requests the page for the first time, in your case the reload. This cookie is stored in the users browser and isn't available to your script running on the server until the next request, or in your case the next reload.

Upon the next request the browser sends that cookie to the server and the array $_COOKIE will have the value that you initially set and the browser sent back upon the second request.

@Will Soares 2014-01-05 22:18:30

Using ob_start() and ob_flush() you can send the cookie to client and retrieve it in the same run time. Try this:

setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . $_COOKIE['uname'];

@Paul DelRe 2014-05-16 13:29:53

This doesn't seem to work (PHP 5.4 w/ nginx). Can you please expand?

@Jason McCreary 2010-07-12 16:17:20

$_COOKIE is set when the page loads, due to the stateless nature of the web. If you want immediate access, you can set $_COOKIE['uname'] yourself or use an intermediate variable.

For example:

if (isset($_COOKIE['uname'])) {
    // get data from cookie for local use
    $uname = $_COOKIE['uname'];
else {
    // set cookie, local $uname already set
    setcookie('uname', $uname, time() + 1800);  

@pathfinder 2013-03-28 02:14:13

this does not make the cookie accessible before a page refresh... see Mark Baker's answer further down for that :)

@Jason McCreary 2013-03-28 14:13:33

That's not true. I've made the assumption, based off the OP's code, that they use $uname in their script. Whereas Mark Baker uses $_COOKIE['uname'] directly.

@pathfinder 2013-03-28 18:06:57

I'm sorry I said it a bit wrong. For my purposes, which are for an asynchronous script, setting $_COOKIE did not actually set the cookie and send it back to the browser (I needed the cookie there too), it only made it available in my script. You need to use setcookie() too, which Mark Baker's answer does. Plus his code is a lot shorter and more useful to people coming here from a google search.

@Jason McCreary 2013-03-29 17:54:05

I use setcookie(). This answer may not meet your exact needs. But that doesn't make it wrong. The OP and SO have found this answer to be useful.

@Pratik 2015-12-09 04:36:10

You mean to say. to access cookie value , Page(php file) needs to be accessed twice. 1st time to set cookie, and 2nd time to access the set cookie. Correct?

@Isthar 2017-01-26 15:51:19

I don't understand why this answer is marked as "the answer". It doesn't explains how to use the cookie directly, and the code provided is like the same OP posted. After setcookie() in that code it is not possible to access $_COOKIE['uname']

@Mark Baker 2010-07-12 16:18:10

The cookie isn't set until the response is sent back to the client, and isn't available in your PHP until the next request from the client after that.

However, when you set the cookie in your script, you can do:

setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;

@dawoodman71 2015-07-21 22:12:26

Very simple solution. Thanks!

@martinedwards 2015-09-24 15:19:31

Great stuff. I wonder how the second line sets the expiry time when it's not passed in?

@Mark Baker 2015-09-24 15:21:53

@martinedwards The second line doesn't set any expiry time.... it's set for the duration of the request; in exactly the same way that a cookie value passed in with a request from a browser exists for the duration of the request

@Shan 2015-11-23 07:52:55

@MarkBaker Simple Solution !! Thanks a lot

@Pratik 2015-12-09 04:36:34

You mean to say. to access cookie value , Page(php file) needs to be accessed twice. 1st time to set cookie, and 2nd time to access the set cookie. Correct?

@Pratik 2015-12-09 04:59:39

Please elaborate difference between your answer and Jason McCreary's

@Isthar 2017-01-26 15:52:02

This is a bad practice as @witrin suggests later.

Related Questions

Sponsored Content

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

7 Answered Questions

[SOLVED] How does PHP 'foreach' actually work?

1 Answered Questions

[SOLVED] setcookie() in php showing undefined index error

13 Answered Questions

[SOLVED] How do I expire a PHP session after 30 minutes?

  • 2009-02-06 13:14:14
  • Tom
  • 939304 View
  • 1028 Score
  • 13 Answer
  • Tags:   php session cookies

1 Answered Questions

[SOLVED] Using setcookie() to expire a cookie variable vs using $_COOKIE = array();

  • 2017-10-27 03:19:15
  • Daniel Long
  • 77 View
  • 0 Score
  • 1 Answer
  • Tags:   php cookies

1 Answered Questions

[SOLVED] asking about the cookie after logout

  • 2016-02-08 13:49:43
  • Praveen Pachauri
  • 37 View
  • 0 Score
  • 1 Answer
  • Tags:   php cookies

2 Answered Questions

[SOLVED] can't read cookie value after browser close and reopen, in php

1 Answered Questions

PHP Cookie lost after browser closes - Browser = Default Settings

  • 2011-09-16 20:44:08
  • Miko
  • 1693 View
  • 3 Score
  • 1 Answer
  • Tags:   php cookies

Sponsored Content