1

I tried many ways to set a cookie, but when I get the cookie the value's not set. My code is placed before the <!DOCTYPE html>:

<?php 
    $url          = explode('/', $_GET['url']); 
    $ref          = $url[1];
    $cookie_name  = "refid";
    $cookie_value = $ref;
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/", "", 0); 
?>

The $url[1] is set, I can see it in print_r() the problem is getting the cookie from a different page the calling code is:

<?php 
    if (!isset($_COOKIE['refid'])) {
        echo "<br/>Cookie named refid is not set!";
    } else {
        echo "<br/>Cookie refid is set!<br>";
        echo "Value is: " . $_COOKIE['refid'];
    }
?>

Please help to resolve my problem.

Joshua
  • 5,032
  • 2
  • 29
  • 45
  • To debug, open F12 in your browser, turn on recording and check to save log between pages. What does the set-cookie header look like in the log? – Dave S May 31 '17 at 04:36
  • it may help https://stackoverflow.com/questions/24662580/php-setcookie-not-working – Felix May 31 '17 at 04:38
  • Try this `setcookie($cookie_name, $cookie_value, time()+3600*24); Cookie named refid is not set!"; } else { echo "
    Cookie refid is set!
    "; echo "Value is: " . $_COOKIE['refid']; } ?>`
    – Arshad Shaikh May 31 '17 at 05:09

1 Answers1

0

Add this line:

$_COOKIE[$cookie_name] = $cookie_value;

after you set the cookie:

<?php 
    $url=$_GET['url'];
    $url=explode ('/',$_GET['url']); 
    $ref=$url[1];
    $cookie_name = "refid";
    $cookie_value = $ref;
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/", "", 0);
    $_COOKIE[$cookie_name] = $cookie_value;
?>

The setcookie() does not update the current $_COOKIE variable, which will be instantiated when the script loads. The variable will first be updated next time you load the script.

Jogge
  • 1,654
  • 12
  • 36