How to set random cookie value using rand function in PHP
I don\'t want to change the value while page refreshed when it once assigned.. until cookie destroy
My
if(!isset($_COOKIE['lg'])) {
setcookie('lg', rand(1,10000), time() + (86400 * 30), "/"); // 86400 = 1 day
}
echo $_COOKIE['lg'];
You can check if it is not set then set it.
<?php
define('COOKIE_KEY', 'COOKIE_KEY');
if (!array_key_exists(COOKIE_KEY, $_COOKIE)) {
setcookie(COOKIE_KEY, mt_rand(1, 10), time()+3600);
}
Your set cookie code is incorrect and the cookie time is only 1 second
change your code as follows...
<?php
//cookie_start();
global $random;
$random= rand(0, 9999999);
if(!isset($_COOKIE['user_cookie'])) {
setcookie('user_cookie',$random, time() + (86400), "/");//86400 = 1 day
}
else {
echo "Cookie '" . $_COOKIE['user_cookie'] . "' is set!<br>";
}
exit();
?>