How to set random cookie value using rand function in PHP

前端 未结 3 823
情深已故
情深已故 2021-01-24 19:16

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

相关标签:
3条回答
  • 2021-01-24 19:34
    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.

    0 讨论(0)
  • 2021-01-24 19:43
    <?php
    define('COOKIE_KEY', 'COOKIE_KEY');
    if (!array_key_exists(COOKIE_KEY, $_COOKIE)) {
        setcookie(COOKIE_KEY, mt_rand(1, 10), time()+3600);    
    }
    
    0 讨论(0)
  • 2021-01-24 19:53

    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();  
    ?> 
    
    0 讨论(0)
提交回复
热议问题