Cookie is not set when a variable is used for a cookie name

On my server when using the code:

<?php
$expire=time()+60*60*24*360;

$cookie_name = 'user';
$cookie_value = "John";
setcookie($cookie_name, $cookie_value, $expire, "/");

$cookie_value = "Jane";
setcookie('userb', $cookie_value, $expire, "/");

print_r($_COOKIE);
?>

      

The first cookie is not set and the second. For some reason, it seems like using a variable to identify the name of the cookie prevents it from being set. This problem does NOT occur on my localhost (everything works as expected). So I'm not even sure where to start.

+3


source to share


3 answers


It looks like it was because I had:

<!DOCTYPE html>

      



before <?php

For some reason, works fine locally, but not on my server. Any suggestions?

+2


source


You cannot use more than one setcookie function.



<?php
$expire=time()+60*60*24*360;
$cookie_name = 'user';
$cookie_value = "John";
setcookie($cookie_name, $cookie_value, $expire, "/");
//$cookie_value = "Jane";
//setcookie('userb', $cookie_value, $expire, "/");
print_r($_COOKIE);
?>

      

0


source


change the parameter of the setcookie function and then try it.
eg.

$expire=time()+60*60*24*360;
$cookie_name = 'user';
$cookie_value = "John";
setcookie($cookie_name, $cookie_value, $expire, "/");

$cookie_value1 = "Jane";
setcookie('userb', $cookie_value1, $expire, "/");

print_r($_COOKIE);

      

0


source







All Articles