Forum Moderators: coopster
I am having trouble managing cookies in php, could someone please have a look and sort this out or suggest a better way to do it.
I want to save an ID in the cookie on my site for 30 days. The Id comes in the URL when the user clicks the advert of my site displayed on an affiliate site. The problem is, If the user comes back on the site through a different affiliate and bring a different ID then the previous cookies should be deleted and a new cookie should be placed for 30 days again.
I can set the first cookie but i'm not able to delete it and place a new one. please see the code below
//set a 30 days cookie.
//if the user's comming from different affiliate then overwrite the existing cookieif(isset($_GET['uid'])){
if(!isset($_COOKIE['aff_uid']) or $_COOKIE['aff_uid']<>$_GET['uid']){
$hostname = $_SERVER['HTTP_HOST'];
setcookie("aff_uid", "", time()-3600,"/", "$hostname");
$cookie_life = time() + 2592000; //30 days
setcookie("aff_uid", $_GET['uid'], $cookie_life,"/", "$hostname");
}
}
when i display the cookie value on a different page it always shows me the old value.
Many Thanks,
Zeeshan. :(
The second if statement is all about if there is not a coookie set. You need and else like this:
if(isset($_GET['uid'])){
if(!isset($_COOKIE['aff_uid']) or $_COOKIE['aff_uid']<>$_GET['uid']){
$hostname = $_SERVER['HTTP_HOST'];
setcookie("aff_uid", "", time()-3600,"/", "$hostname");
$cookie_life = time() + 2592000; //30 days
setcookie("aff_uid", $_GET['uid'], $cookie_life,"/", "$hostname");
}else{
set your cookie
}
Im not sure why you are doing this. I would do this code i think:
if(isset($_GET['uid'])){
$hostname = $_SERVER['HTTP_HOST'];
setcookie("aff_uid", "", time()-3600,"/", "$hostname");
$cookie_life = time() + 2592000; //30 days
setcookie("aff_uid", $_GET['uid'], $cookie_life,"/", "$hostname");
}
This will reset the cookie if their is one sent in url. You may want to destroy the cookie first though, using unset().
i was doing that because there are two conditions on which i'll create a new cookie.
1- either theres not cookie placed on the system
2- or the new value is different from the old value
if there exists a cookie with the same value then it should be left as it is.
anyway, the problem is sorted now. for some reason "hostname" was creating the problem. i'ev removed it now and the setcookie() works fine now.
Thanks for your help,
Zeeshan.