troubleshooting Question

Read cookie, set cookie, pass cookie val all in one page

Avatar of betagirl
betagirl asked on
PHPScripting Languages
2 Comments1 Solution904 ViewsLast Modified:
Hello  Experts -

I need to do something on a single page and I'm having a problem setting and accessing the cookie.  We have external URLs that pass in the string a variable - $refid - so for example a link goes to:

On page.php I need to grab the value of refid, set a cookie equal to that value, and then pass that same value in another URL on page.php - ex. <a href="<?=$refid?>">link</a>

Here's how I currently have the code, and the problem I'm having is that the cookie does not appear to get set (or is not being read back in) when I revisit the page.  So in the event the user does not click on the link that passes the refid when they first hit the page, if they come back in a week, I want that value remembered and passed.  

My code (for page.php in example above)

if (isset($_COOKIE["referral"])) {
  $refid = $_COOKIE["referral"];
 } else {

      $refid = $_GET['ref'];
      setcookie("referral", "$refid", time()+86400*30*2);
      $refid = $_COOKIE["referral"];

So after this code, later down the page there is this link:
 <a href="<?=$refid?>">link</a>

But with the current code, the $refid var is only getting passed in the URL if the user comes to the page with it in the URL (ie via - I don't know if the cookie is not being set properly, or not being read properly.

Thanks in advance!

Enterprise Web Developer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros