How to delete a cookie when a user leaves a page?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ljCharlie
Forum Contributor
Posts: 289
Joined: Wed May 19, 2004 8:23 am

How to delete a cookie when a user leaves a page?

Post by ljCharlie »

I know how to delete a cookie but my question is, how do I delete a cookie at the time the user leaves a certain page? As long as the user is still on a profile page, let's say, keep the cookie but as soon as the user leaves the profile page to a different page then delete the cookie so I can reset the cookie to a different value. Can this be done? If so, will you mind show me how?

Thank you,

ljCharlie
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

set the expiry-date to some date in the past or update the value of your cookie.
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

No, that wouldn't work because headers have been sent.
ljCharlie
Forum Contributor
Posts: 289
Joined: Wed May 19, 2004 8:23 am

Post by ljCharlie »

Many thanks for your response. Okay, let's say I set the cookie at the begining of the page called profile.php. Now when the user browse to the page called login.php, where do I set the expire date, on the begining of the login.php page or at the very end of the profile.php page?

By the way, how do I update the value in the cookie?

ljCharlie
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

Update the value by overwriting it (set the cookie again).

You'd have to set the expire date at the beginning (before any HTML) of the next page the user hits.
Last edited by Grim... on Tue Jun 08, 2004 9:18 am, edited 1 time in total.
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

At the top, otherwise you get the header-error.

Cookie tutorial#1: http://www.juicystudio.com/tutorial/php/cookies.asp
Cookie tutorial#2: http://www.spoono.com/php/tutorials/tut ... rl=cookies
Cookie tutorial#3: http://www.zend.com/zend/tut/feedback.php

and, lastly:

viewtopic.php?t=11417
evilMind
Forum Contributor
Posts: 145
Joined: Fri Sep 19, 2003 10:09 am
Location: Earth

Post by evilMind »

use javascript to delete the cookie.
eg:

Code: Select all

<body onunload="document.cookie = 'yourCookieName=yourCookieValue; expires=Sat, 10-Jun-2000 00:00:00 GMT;';">
... Your page ...
</body>
ljCharlie
Forum Contributor
Posts: 289
Joined: Wed May 19, 2004 8:23 am

Post by ljCharlie »

Many thanks for all your help. I'll give that a try.

ljCharlie
Post Reply