How to set random cookie value using rand function in PHP

浪子不回头ぞ 提交于 2019-12-11 10:38:44

问题


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 code is as follows

<?php 
    global $random; 
    $random= rand(0, 9999999); 
    if(!isset($_COOKIE[$random])) {
        setcookie('user_cookie',$random, time() + (1), "/"); echo $_COOKIE[$random];
    }
    else {
        echo "Cookie '" . $_COOKIE[$random] . "' is set!<br>"; 
    }
    exit(); 
?> 

回答1:


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.




回答2:


<?php
define('COOKIE_KEY', 'COOKIE_KEY');
if (!array_key_exists(COOKIE_KEY, $_COOKIE)) {
    setcookie(COOKIE_KEY, mt_rand(1, 10), time()+3600);    
}



回答3:


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();  
?> 


来源:https://stackoverflow.com/questions/47709411/how-to-set-random-cookie-value-using-rand-function-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!