Jump to content

[SOLVED] How to replace cookie value without changing expiry date?


blurredvision

Recommended Posts

I have a project where I'm needing to change the value of an already existing cookie, but I have a set expiry date that I don't want to change.  For example, I have a cookie that has a value of 'car', and is set to last for one hour.

 

setcookie("cookie1", "car", time()+3600);

 

In 20 minutes, I will want to change $_COOKIE['cookie1'] from 'car' to 'truck'.  BUT, I want to make sure that the cookie will still cease to exist in 40 minutes and not reset back to an hour when I update the cookie with a new value.

 

How do I do this, or can I do this?  I've not had much experience with cookies, so thanks for any learning :).

I don't think there's a way to officially retrieve when a cookie is due to expire, but you can do something like this:

 

<?php
$name = "somename";
$expire = time()+3600;
$value = "somevalue|$expire"; 
setcookie($name,$value, $expire);
?>

 

And then explode($_COOKIE['somename']) to find out what you set the expiration as and subtract the current time() from it, to find out how much time is left, and use that as the new $expire.

unfortunately PHP cannot read the times a cookie is going to expire.....

 

1. Simple workaround for this is to just setup another cookie that stores the time that one will expire and use that ones value to reset the other cookie.

 

 

2. Use the Above Method

 

OR

 

3. Use a database with sessions...much more secure :) and you can manipulate it till the cows come home

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.