Dheeraj
Dheeraj

Reputation: 323

PHP redirect using cookies and headers

I was learning PHP and trying to redirect pages based on if the cookie is set or not so below is the code I used to set the cookie on the first page

<?php
setcookie("test","logged in",time()+60,'/');
?>

Now on the testing page I delete the cookie but it doesn't get deleted below is the code

<?php
setcookie("test", 0, time()-(60*60*24*7));

if(isset($_COOKIE['test']))
{
    echo "u had logged in";
}
else
header("Location: index.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>

</body>
</html>

What exactly is the problem ?

Upvotes: 2

Views: 4652

Answers (2)

John Parker
John Parker

Reputation: 54415

Cookies are only set when a page is transmitted to the browser and are only read when they're sent to the server as a part of a HTTP request.

As such:

  1. If you delete a cookie, it won't disappear until the next page load.

  2. If you set a cookie, the value can't be read until the next page load.

A common way of dealing with this is to set/delete a cookie and then perform a re-direct.

Upvotes: 3

eykanal
eykanal

Reputation: 27017

Changes made to cookies are only visible to the server on refresh. If you reload the testing page, you shouldn't see the "logged in" text.

Upvotes: 0

Related Questions