Reputation: 63
I can't delete a cookie with my php code. When I press logout
the page refreshes but the cookie is still there.
<?php
if (isset($_COOKIE["admin_login"])) {
echo "Cookie: ".$_COOKIE["admin_login"]."<br>";
}
if (isset($_GET["logout"])) {
setcookie("admin_login", "", time()-3600);
unset($_COOKIE['admin_login']);
}
?>
<html>
<body>
<a href="?logout">Logout</a>
</body>
</html>
Upvotes: 2
Views: 892
Reputation: 63
Thank you for your answers. After finding no solution i tried to switch to SESSION.
After some research i made it works great. Thank you all for helping me.
If someone is interested, here is my final code.
<?php
session_start();
if (isset($_GET["logout"])) {
session_unset();
session_destroy();
header("Location: ../login.php");
}
if (isset($_SESSION["admin_login_session"])) {
echo "Cookie: ".$_SESSION["admin_login_session"]."<br>";
} else {
header("Location: ../login.php");
}
?>
<html>
<body>
<a href="?logout">Logout</a>
</body>
</html>
Upvotes: 0
Reputation: 2002
This is likely happening because you're outputting data before setting cookie.
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).
if (isset($_COOKIE["admin_login"]))
anything_that_doesnt_output_text(); // text was causing problem most likely.
if (isset($_GET["logout"]))
setcookie("admin_login", "", time()-3600); // also, no unsetting
Upvotes: 1