PHP - setcookie () not working

I have this page that sets cookie and echos from a string if you check the box. The line prints correctly, but the cookie is never set, and I have no idea why.

<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>
  <?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'];
  ?>

Does anyone know why the above code is not working?

+4
source share
3 answers

PHP script, PHP script. , $_COOKIE cookie, HTTP-, script. cookie, // script. NEXT.

- $_SESSION, session_start().

, $_COOKIE , , .

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

, , . , cookie , .

- cookie.

// set cookie
setcookie("cookie", "off", time()+3600*24);
// not available because this cookie was not sent with the page request.
echo $_COOKIE['cookie'];
+2

PHP http://php.net/manual/en/function.setcookie.php:

, setcookie() . setcookie() , . , cookie.

In other words, the function setcookie()does not work because it is inside the page. If you want it to work, you will need to put this function in front of the page, especially before any headings.

Do it:

<?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>
+2
source

Source: https://habr.com/ru/post/1547820/


All Articles