Jump to content

A little help with setting up cookies


imgrooot

Recommended Posts

Here's a scenario.

 

I am setting up a sponsor referral link. If any user signs up on the site through that referral link, they will be matched with the sponsor of that referral link. Normally I can do this using a simple GET method but I want to use cookies so that the referral link will be valid for 30 days. So if a user decides to come back to the site  a week later, they will still be matched with that sponsor assuming they haven't deleted their cookies.

 

For eg.

// referral link
mysite.com/signup?sponsor=john 

Here is my cookie code. The issue i am having is that if I go to a different page on the site and come back to the signup page, the cookie gets reset or becomes invalid.  Can you tell me what i'm doing wrong? Do I have to use the database to store the cookies or what?

  $get_user = $_GET['sponsor'];

  $number_of_days = 30 ;
  $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;
  setcookie( "sponsor", $get_user, $date_of_expiry);

  if(isset($_COOKIE['sponsor'])) {
      echo 'set';
  } else {
      echo 'not set';
  }
Link to comment
Share on other sites

Are you executing that same code when you come back?  If so, you are writing over your cookie.  Based on your error configuration, you should be getting a warning stating something like index sponsor not defined.  Use an IF statement to hope over it if $_GET['sponsor'] is not set (and based on your desire, also hope over it if the cookie is already set and you  don't want the second link to override the first one).

Link to comment
Share on other sites

Are you executing that same code when you come back?  If so, you are writing over your cookie.  Based on your error configuration, you should be getting a warning stating something like index sponsor not defined.  Use an IF statement to hope over it if $_GET['sponsor'] is not set (and based on your desire, also hope over it if the cookie is already set and you  don't want the second link to override the first one).

 

You are correct. I only have to set the cookie if there is a sponsor parameter. I retrieve the cookie if the parameter is not set. Here is the updated code and it works.

$get_user = $_GET['sponsor'];

if(!empty($get_user)) {

  $number_of_days = 365;
  $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days;
  setcookie( "sponsor", $get_user, $date_of_expiry);

} else if(empty($get_user)) {
  if(isset($_COOKIE['sponsor'])) {
    // find the set cookie
    $user_cookie = $_COOKIE['sponsor'];
  }
} else {}
Link to comment
Share on other sites

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.