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 :).

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.