Search code examples
phpsetcookieundefined-index

Undefined Index: Array in Name parameter of setCookie


I know that Undefined Index questions have been asked and answered before. But please humor me for a second. I couldn't find the answer to this specific case. (And an unusual case it is.)

This works without a problem...

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

$expiry = time()+60*60*9000;
setcookie('loggedin', 'foo', $expiry);

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

?>

...producing this output

sessionvalue 1
cookievalue foo

However, when I change the Name parameter in the setCookie to an array like so:

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

  $expiry = time()+60*60*9000;
  setcookie('cookievalue[loggedin]', 'foo', $expiry);

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

?>

I get the Undefined Index notice like so:

sessionvalue 1

Notice: Undefined index: cookievalue[loggedin] in /Applications/XAMPP/xamppfiles/htdocs/simpleauth/headersessioncookie.php on line 13
cookievalue

What can I declare, and how, to avoid the "Notice" in the second case?


Solution

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

    should be

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