1

I am setting up an affiliate link area for my site and need to be able to store a URL query string into a cookie that expires in a 7 days.

Users will click on a link like: http://examplesite.com?afil=randomvalue.

I want to pull the key 'afil' and the value 'randomvalue' and put it in a cookie.

This will be used later down the road in another area of the site and I can't keep it in the URL.

I found this post: Set a Cookie based on url Parameter

But it doesn't seem to do what I want or set an expiration date. I am not sure if it is best to use php or javascript for this but I was planing on using php to pull the data later.

UPDATE:

I added this code to my dev site here: http://inventivewebdesign.com/dev/about?afil=great

<?php 
     $value=$_GET['afil']; //the value from the url
     setcookie("afilCookie", $value, strtotime( '+7 days' ));  /* expire in 7 days */
     echo "Cookie = " . $value;
?>

As you can see, it does display the cookie value (I added it right at the end of my header.php file which puts it in the body). For some reason it doesn't add it to my cookies when I view them.

Also, does this need to be made conditional for if there is no afil value?

Community
  • 1
  • 1
MattM
  • 3,089
  • 7
  • 40
  • 62

1 Answers1

3

http://php.net/manual/en/function.setcookie.php

$value=$_GET['afil']; //the value from the url

setcookie("TestCookie", $value, strtotime( '+7 days' ));  /* expire in 7 dasy */

regarding its location with in the code flow the manual says:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

  • This kind of works but it doesn't look like it actually sets a cookie. It does pull the value in from the url though. Check my update above. – MattM Jan 05 '17 at 23:56
  • @MattM i see no update. I'm not suer how it can "kind of work" it either does or does not. if not you need to show how your setting the cookie, and how your checking for it –  Jan 05 '17 at 23:58
  • @MattM you have the above code before ANY output on that page? –  Jan 06 '17 at 00:08
  • That was it. I added it to the area and it worked thanks! – MattM Jan 06 '17 at 00:21