如何在PHP中使用rand函数设置随机cookie值

问题描述:

如何在PHP中使用rand函数设置随机cookie值

How to set random cookie value using rand function in PHP

我不希望在页面刷新后更改值(一旦分配了它)。直到cookie销毁

I don't want to change the value while page refreshed when it once assigned.. until cookie destroy

我的代码如下

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


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.