简体   繁体   English

如果不存在值,则插入Cookie

[英]Insert cookie if value is not present

I am trying to insert cookie. 我正在尝试插入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 编辑代码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. 使用该代码,仅当未设置cookie时,才定义$current_value Set $current_value in the else part. 在else部分中设置$current_value Concatenate the cookie instead of $current_value . 连接cookie而不是$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));
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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