Set cookies to expire at end of day

Hello, im having a problem thinking how to work out this problem, im setting cookies in php like this simple bit of code:

setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */

thats set to expire in 1 hr, i want to have php some how find out how many hrs are left in the day and then put that into the cookie so when the clock strikes midnight it will go away, does anybody no how to get php to do this?

setcookie("TestCookie", $value, mktime(24, 0, 0) - time());

so that will expire at the end of the day?


sweet thanks

The mktime() bit says “The time at 24:00:00 today” (i.e. next midnight) and the time() bit is the time now, so the result of the subtraction is the time between now and midnight.

When I use this it doesn’t set a cookie at all. Any suggestions as to what might be wrong?

Does your browser accept cookies? Are you doing this before outputting any HTML or whitespace? Cookies are set when headers are sent so you can’t set a cookie after outputting any HTML.

Raffles, when I use the following code it works.

setcookie ("name", yes, time()+60*60*12, "/", "")

When I replace time()+606012 with mktime(24, 0, 0) - time() it doesn’t even set a cookie.

I’ve been trying to make it expire at midnight so it would be great if you could point out what I’ve done wrong. :blush:

That’s because mktime(24,0,0) - time() is a few hours after midnight on the first of January 1970. So if it’s a time in the past, the cookie isn’t set.

The correct thing is simply mktime(24,0,0) without time() being subtracted. Got it wrong the first time, forgot cookies need the actual time, not the time from now. I guess I’d better let bkflash know about this…

Cool, thanks.

Forgive my ignorance, but would that code not be using the time from the server and not from the client? Time zone differences could cause strange behaviour.


Good point, mcmunt. PHP is server-side scripting, whereas Javascript is client-side.

You’ll need to use Javascript to use the client’s time.