0

I use cookies (I've tried both PHP and Javascript) to "send" values between two pages. On the first page I do that:

setcookie("url", $url, time()+3600);

Then I'm doing a redirect with Javascript:

window.location.href =location.protocol+'//'+document.domain+'/example.php';

And then in example.php I do that:

<?php
   echo $_COOKIE['url'];
   $url = $_COOKIE['url'];
   setcookie ("url", "", time() - 3600)
?>
<script
   type="text/javascript" src=<?php echo $url?>>
</script>

The value of $url changes depending on some conditions before I set the cookie. The problem is that cookie has always the same value. What I'm doing wrong?

  • 1
    All calls to `setcookie` must be done *before* anything is sent to the browser. That call to `echo` is prohibiting setcookie from working. Turn on error reporting. Look at the `return value` section of [the setcookie docs](http://php.net/manual/en/function.setcookie.php) – castis May 18 '16 at 20:33
  • 1
    Possible duplicate of [PHP - setcookie(); not working](http://stackoverflow.com/questions/20316870/php-setcookie-not-working) – castis May 18 '16 at 20:35

1 Answers1

0

Setcookie needs to happen before any output on both pages.
On example.php you have an echo above setcookie, remove that.
Do you have any output on the first page too before setcookie? Then change the order.

The reason the value does not change is because the setcookie fails due to output before it.

Good luck!

Andreas
  • 23,610
  • 6
  • 30
  • 62