简体   繁体   中英

Insert cookie if value is not present

I am trying to insert cookie. The logic is simple as:

  • Check if the value is present .
  • If not, insert new value with comma separated form.

I have tried some code but I could not able to get a correct result.

In this code a new value should be inserted, which is happening but not getting old value.

Edited Code 2

        $current_value = '';
 if(!isset($_COOKIE['blog_id_cookie'])){
     setcookie('blog_id_cookie', $id);
     $current_value[] = $_COOKIE['blog_id_cookie'];
 } else {
     $current_value = explode(',', $_COOKIE['blog_id_cookie']);
 } 
 if(!in_array($id, $current_value)){
     $current_value[] = $id;
     $cookie_name  = "blog_id_cookie";
     setcookie($cookie_name, implode(',', $current_valu));
 }

With that code $current_value will be defined only if the cookies is not set. Set $current_value in the else part. Concatenate the cookie instead of $current_value . Try with -

Update

 $current_value = '';
 if(!isset($_COOKIE['blog_id_cookie'])){
     setcookie('blog_id_cookie', $id);
     $current_value[] = $_COOKIE['blog_id_cookie'];
 } else {
     $current_value = explode(',', $_COOKIE['blog_id_cookie']);
 } 
 if(!in_array($id, $current_value)){
     $current_value[] = $id;
     $cookie_name  = "blog_id_cookie";
     setcookie($cookie_name, implode(',', $current_value));
 }

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