PHP – setcookie() not working

PHP superglobals are populated at script start-up time, and then are NOT modified or touched by PHP again for the life of the script. That means $_COOKIE represents the cookies that were sent to the server in the http request that fired up the script. It will NOT show any cookies you've added/changed/deleted during the life of the script. Those changes will only show up on the NEXT request.

The only exception to this is $_SESSION, which is populated when you call session_start().

If you need those values to be in $_COOKIE immediately, you'll have to add them manually, e.g.

setcookie('cookie', $value, ....);
$_COOKIE['cookie'] = $value;

According to the PHP Manual at http://php.net/manual/en/function.setcookie.php:

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.

In other words, the function setcookie() is not working because it is inside the page. If you want it to work, you will need to put that function before the page, specifically before any headers.

Do this:

<?php
  if ( isset($_POST['checkbox']) ) {
     setcookie("cookie", "on", time()+3600*24);
     echo "You checked the checkbox and a cookie was set with a value of:<br>";
  } else {
     setcookie("cookie", "off", time()+3600*24);
     echo "You didn't check the checkbox and a cookie was set with a value of:<br>";
  }

  echo $_COOKIE['cookie'];
?>
<!doctype html>
<html>
  <head>...</head>
  <body>
      <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
         <label for="checkbox">Option 1:</label>
         <input type="checkbox" name="checkbox" id="checkbox"><br>
         <input type="submit" name="submit" value="Submit">
      </form>
  </body>
</html>