简体   繁体   English

使用PHP从Cookie删除值

[英]Delete a value from cookie with php

I am storing product id-s in a cookie with php. 我将产品ID-S存储在PHP的Cookie中。 (These are the favorite products on a webshop.) (这些是网上商店中最受欢迎的产品。)

I added many products as favorit, so my cookie looks like: 12,55,120,43 我添加了许多产品作为收藏夹,因此我的Cookie看起来像:12,55,120,43

What i know, that the $_COOKIE[$cookie_name] is not an array. 我知道, $_COOKIE[$cookie_name]不是数组。 (checked with is_array function) (通过is_array函数检查)

How can i delete a product id from that cookie? 如何从该Cookie中删除产品ID? I send the id that i want to delete with ajax to this php file: 我将要使用ajax删除的ID发送到此php文件:

    if(isset($_POST['id']))
{
    $id = intval($_POST['id']);

    $cookie_name = "kedvenc_termek";
    if(isset($_COOKIE[$cookie_name]))
    {
        echo $_COOKIE[$cookie_name];
    }

}

This should delete or invalidate cookie 这应该删除或使cookie无效

// set the expiration date to one hour ago

setcookie($cookie_name, " ", time() - 3600);
?>

Unset your cookie: 取消设置您的Cookie:

unset($_COOKIE[$cookie_name]);

Set your cookie null: 将您的Cookie设置为null:

setcookie($cookie_name, null, -1, '/');

If I understand you correct you have a string stored in the cookie like 12,55,120,43 and you want to remove one of them using $_POST['id'] ? 如果我了解您的要求,您在cookie中存储了一个字符串,例如12,55,120,43并且您想使用$_POST['id']删除其中之一? Since it's a string I believe the best option is preg_replace() this gives you the benefit over str_replace that you can create a pattern to remove. 因为它是一个字符串,所以我认为最好的选择是preg_replace(),它比str_replace更具优势,您可以创建一个删除模式。

$id = $_POST['id'];
$cookie_name = "kedvenc_termek";
$_COOKIE[$cookie_name] = preg_replace("/\b(" . preg_quote($id) . ",)\b/", "", $_COOKIE[$cookie_name]);
echo $_COOKIE[$cookie_name];

If you want to store the new string in the cookie then be sure to do that before you echo the value since you can't set a cookie after an output. 如果要将新字符串存储在cookie中,请务必在回显该值之前执行此操作,因为在输出后无法设置cookie。

Example: https://3v4l.org/RQH4o 示例: https//3v4l.org/RQH4o

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

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