How to Unset Cookie in PHP

Remove a cookie

You May Try this

if (isset($_COOKIE['remember_user'])) {
unset($_COOKIE['remember_user']);
setcookie('remember_user', null, -1, '/');
return true;
} else {
return false;
}

how to unset cookie in PHP?

The solution to this problem was that the I needed to set the correct path to unset the cookie since I was unsetting it from a different file that I originally set it in.

I found out which path I needed to use for the unset by looking for the cookie inside my browser cookies, and once I found the cookie inside my browser, the path was listed near the cookie. So I then set the path to the cookie like so:

setcookie("user_id", $user_id, time() - 1, "/social_learning/site_pages");

The last parameter is the path. And it worked.

My original setcookie looks like this:

setcookie("user_id", $user_id, time() + 7200, "");

How can I delete a php Cookie

Actually, there is not a way to directly delete a cookie. Just use setcookie with expiration date in the past.

$cookie_name = 'pontikis_net_php_cookie';
unset($_COOKIE[$cookie_name]);
// empty value and expiration one hour before
$res = setcookie($cookie_name, '', time() - 3600);

How to delete/unset a cookie on php?

you can unset cookies this way only may -1 not work

try this

setcookie ("user", "", time() - 3600);

Php cookie won't unset/delete - can't logout

I found the answer. It's a stupid answer too. Here is the full code file i was using for logout.

<?php

require_once ('Connection.php');

header('Refresh: 0;');

if (!isset($_COOKIE['Username'])){
header('Location: LoginFunctions.php');
} else {
setcookie('Username', '', time()-60*60*24*90, '/', '', 0, 0);
unset($_COOKIE['Username']);
header('Location: index.php');
}

?>

The problem, which i can't show here, was that the opening php tag had a single line break on it, meaning that it started on line 2. Why it was like this initially i don't know, but that small error meant that it worked on localhost and didn't work on godaddy. How frustrating. At least i've fixed the problem now.

For future use, for those stuck with the same issue, apparently godaddy (or most hosting sites) require that any cookie adding, editing or deleting occur from line 1 onwards, therefore the php tag which includes the cookie must be on line 1, no html code can preceed this php tag, or any line breaks, the php tag has to start on line 1.

cookie unset not working properly

I don't know what is the problem but I used jquery plugin for cookie delete {https://github.com/carhartl/jquery-cookie}. I included jquery.cookie.js and then on logout click I deleted the cookie set as $.removeCookie('remember_me') and it's working fine.Thanks for the suggestions and help.



Related Topics



Leave a reply



Submit