Mohamed Omar Mohamed Omar - 7 days ago 6
PHP Question

Why this code works fine only on local server?

I'm trying to learn how to set cookies, and the following code works fine on local server but for some reason it doesn't on live server. Here is the code

<?php
$test = 'false';
if (isset($_COOKIE['test'])) $test = $_COOKIE['test'];
echo "<p><b>The value of the cookie 'test' is: $test</b></p>";
setcookie('test', 'I love cookies');
?>


I have done some searches and there is someone who had same problem, but he answered him self claiming that he figured out what is wrong. here is his answer :

It's done already. Problem was with setting cookies as headers had already been sent in that file, cookies were not saving. Now done.:)

So, What did he mean by that?

Answer

Did you test both localhost and live server with same browser (with cookies enabled)?

EDIT:

Following your edit, you should set cookies BEFORE you sent ANY output like echo, print_r etc... as setCookie command sends to a browser with headers, and all headers should be sent before output. Your code should look like that:

  $test = 'false';
  if (isset($_COOKIE['test'])) $test = $_COOKIE['test'];
  setcookie('test', 'I love cookies');
  echo "<p><b>The value of the cookie 'test' is: $test</b></p>";

If you really need to perform some action with output BEFORE you set cookie, you can use output bufer:

  $test = 'false';
  if (isset($_COOKIE['test'])) $test = $_COOKIE['test'];

  ob_start();
  echo "<p><b>The value of the cookie 'test' is: $test</b></p>";
  $buffer = ob_get_contents();
  ob_end_clean();

  setcookie('test', 'I love cookies');
  echo $buffer;
Comments