简体   繁体   中英

Create and delete cookies in php

I am trying to create and delete cookie in php but I am unable to do so. I have gone through php official site but even that did not resolve my issue.

The code that I have written:

<?php
$cookie_name = "cookie_id";

if (!isset($_COOKIE[$cookie_name]))
{
    echo "Inside if: ".$_COOKIE[$cookie_name];

    $unique_id = date('ymdhis').''.uniqid('', true);

    setcookie($cookie_name, $unique_id);
    setcookie($cookie_name, $unique_id, strtotime( '+30 days' ) );
    setcookie($cookie_name, $unique_id, strtotime( '+30 days' ) , "/", "www.domain.in", 1);
}
echo "Current: ".$_COOKIE[$cookie_name];

setcookie ($cookie_name, "", time() - 3600);
setcookie ($cookie_name, "", time() - 3600, "/", "www.domain.in", 1);

echo "</br>";
echo "After Reset: ".$_COOKIE[$cookie_name];
?>

Basically I am trying to create and delete the cookie on the same page and then recreate it on next page load.

I have already referred: [ http://us3.php.net/manual/en/function.setcookie.php][1] but cant get through.

This is what output I get:

Inside if: Current: 
After Reset:

As per the PHP documentation you linked:

Once the cookies have been set, they can be accessed on the next page load

You are trying to read the cookie too quickly, you're setting it and then deleting it before it even makes it to the user.

您可能要尝试删除Cookie

setcookie($cookie_name, null, null);

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