简体   繁体   中英

Checking and setting cookie in a function

I wrote a function that checks if a cookie is set, if not set then it sets the cookie.

Because the cookie is not available straight away, I need to refresh the page once, so I have access to the value.

However, when I am calling the function it just keeps reloading the page. When outside of the function it works correctly. Only when it is inside a function and I call it does it occurs.

function getCookie (){
    if(isset($_COOKIE['ID'])){
        $cookieID = $_COOKIE['ID'];
    }
    else{
        //generate random value for cookie id
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $uuid =  substr($charid, 0, 8)
                 .substr($charid,20,12);

        setcookie( "ID", $uuid, strtotime( '+7 days' ) ); 
        $cookieID = $_COOKIE['ID'];
        echo "<META HTTP-EQUIV='Refresh' CONTENT='0'>  ";
    }
    echo $cookieID;
}

Here's a working php page...

<?php

function getCookie (){
    if(isset($_COOKIE['ID'])){
        $cookieID = $_COOKIE['ID'];
    }
    else{
        //generate random value for cookie id
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $uuid =  substr($charid, 0, 8)
                 .substr($charid,20,12);

        setcookie( "ID", $uuid, strtotime( '+7 days' ) ); 
        $cookieID = $_COOKIE['ID'];

        //just assign the cookie the value as if it was in the header. 
        //no refresh needed.
        $_COOKIE['ID'] = $uuid;

    }
}

?>
<html>
<body>
<?php 
  getCookie();
  echo $_COOKIE['ID']; 
?>
</body>
</html>

Check what excacly isset returns. From Your description seems that simply no cookie is set after first execution of this code. In FireFox You can chcek if cookie is set using firebug tool.

A good idea is to compare also a type of data in any if for excample if(isset($some_var) === true){ instead of if(isset($some_Var)){ . Remember that:

$v = 0;

if($v == 0){ } returns true

if($v === 0){ } returns true

if($v == false){ } returns true

if($v === false){ } return false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM