48

I am working on a multilingual site so I tried this approach:

echo $_COOKIE["lg"];
if (!isset($_COOKIE["lg"]))
    setcookie("lg", "ro");
echo $_COOKIE["lg"];

The idea is that if the client doesn't have an lg cookie (it is, therefore, the first time they've visited this site) then set a cookie lg = ro for that user.

Everything works fine except that if I enter this page for the first time, the first and second echo return nothing. Only if I refresh the page is the cookie set and then both echo print the "ro" string I am expecting.

How can I set this cookie in order to see its value from the second echo on the first visit/page load of the user? Should be without needing to refresh the page or create a redirect.

TRiG
  • 10,148
  • 7
  • 57
  • 107
Teodor
  • 1,285
  • 4
  • 21
  • 37
  • I'd separate the need for client-side cookie (i.e. the $_COOKIE[] array) from a server-side session cookie - the $_SESSION[] array. For further internal use in the code, use the $_SESSION cookie - it is accessible at once after setting. – Hristo May 12 '22 at 19:06

3 Answers3

109

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
Treffynnon
  • 21,365
  • 6
  • 65
  • 98
  • 2
    I would personally recommend against setting `$_COOKIE[]` value. This can trick some other piece of code later that the user did have this cookie. Alternative would be `$lg = (isset($_COOKIE['lg']) ? $_COOKIE['lg'] : 'ro'; echo $lg;` – Ramy Nasr Oct 24 '17 at 15:49
  • Hi Ramy, i hope you been well i now that code was from 5 years ago .but can you be more clear i got invalid syntax as well... – DOMDocumentVideoSource Apr 04 '23 at 21:43
17

Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

Source

Community
  • 1
  • 1
0b10011
  • 18,397
  • 4
  • 65
  • 86
0

If you set a cookie with php setcookie you can see the set and the value of the cookie, as an example, with the developer tools of firefox just in time.

But you need to reload/load the same/next page if you wanna read, get or check the cookie and the value inside to work with that cookie in PHP.

With this example you can choose if you wanna reload the same page with PHP, HTML or JAVASCRIPT.

If the cookie is not accepted or cookies are disabled, a loading loop is obtained and the browser stops loading the page.

LONGVERSION WITH PHP 'header' RELOAD SAME PAGE:

<?php

$COOKIE_SET     = [
     'expires'  => '0'
    ,'path'     => '/'
//  ,'domain'   => 'DOMAIN'
    ,'secure'   => 'true'
    ,'httponly' => 'true'
//  ,'samesite' => 'Strict'
    ];
    
$COOKIE_NAME    = "MYCOOKIE";
$COOKIE_VALUE   = "STACKOVERFLOW";
    
if(!isset($_COOKIE[$COOKIE_NAME])){
    setcookie($COOKIE_NAME, $COOKIE_VALUE, $COOKIE_SET);
    // YOU NEED TO RELOAD THE PAGE ONCE
    // WITH PHP, HTML, OR JAVASCRIPT
    // UNCOMMENT YOUR CHOICE
    
    // echo '<meta http-equiv="refresh" content="0;URL=/">';
    // echo '<script>window.location.replace("/");</script>';
    header("Location: /");
    exit;
  }
else{
    echo ($_COOKIE[$COOKIE_NAME]);
}
  
?> 

SHORTVERSION WITH PHP 'header' RELOAD SAME PAGE:

if(!isset($_COOKIE['MYCOOKIE'])){
    setcookie('MYCOOKIE', 'STACKOVERFLOW');
    header("Location: /");
    exit;
}

echo ($_COOKIE['MYCOOKIE']);
Z0OM
  • 1
  • 4
  • 18
  • 29