Search code examples
phpcookiessetcookie

PHP cookie value not being passed from one page to another


This is in a page called headersessioncookie.php

<?php
  session_start();
    if ( ! isset (  $_SESSION['loggedin'] ) ) {
      $_SESSION['loggedin'] = FALSE;
    }

  $expiry = time()+60*60*9000;
  setcookie('cookie[loggedin]', '', $expiry, "", "", "", TRUE);

  if ( ! isset (  $_COOKIE['cookie[loggedin]'] ) ) {
    $_COOKIE['cookie[loggedin]'] = FALSE;
  }

?>

This is in a page called test.php

<?php
  require_once('headersessioncookie.php'); //start session and cookie

  $_SESSION['loggedin'] = TRUE;
  $_COOKIE['cookie[loggedin]'] = TRUE;

?>

When I run test.php and then run this page below called test1.php ...

<?php
  require_once('headersessioncookie.php'); //start session and cookie

  echo "sessionvalue" . $_SESSION['loggedin'] . '<br>';
  echo "cookievalue" . $_COOKIE['cookie[loggedin]'] . '<br>';

?>

... I get

sessionvalue1
cookievalue

Why don't I get...

sessionvalue1
cookievalue1

...??


Solution

  • Answering my own question. Turns out there were 3 major problems with my code.

    1) I was trying to set the cookie value by doing this:

    $_COOKIE['cookie[loggedin]'] = FALSE;
    

    Turns out one needs to use setcookie() to set the cookie value. Assigning a new value to $_COOKIE will change the value of that variable (within the scope of the same page), but it won't change the value inside the cookie (outside the scope of that page, calling $_COOKIE will yield the value stored in the cookie).

    2) The following is incorrect

    echo "cookievalue" . $_COOKIE['cookie[loggedin]'] . '<br>';
    

    Instead it should be

    echo "cookievalue" . $_COOKIE['cookie']['loggedin'] . '<br>';
    

    3) Cookie necessarily has to be passed a string value. I was trying to pass a value = FALSE which is not a string. Instead, I could have correctly passed a value = 'FALSE'