1

I am working on a website where I use cookies to login and to track whether people have watched a certain page (for view counts). After working on it for a while, I decided to launch the website, and put the site on a server. But while testing a saw that I could not login. I first discovered this while using sessions. I would set the session, but the session would not stay around. After looking through the code, I could not find one issue. So I decided to change this to cookies, which added some useful session customization. I thought: perfect. So I test this code on localhost, and it worked perfectly: no problem at all. So I put this live on the server and again, nothing was set. No cookies, nothing. I've googling for the past two days, without any effort, but nothing shows a working solution for me.

Now, he some useful, found info: I use ob_start and ob_end_flush; I use setcookie($key, $value, strtotime(+1 month), '/'); I tried forcing the cookie by using $_COOKIE[$key] = $value before using the previous line; I made a testscript, consisting of:

session_start();
ob_start();
error_reporting(E_ALL);

if (!isset($_COOKIE['test'])){
    $_COOKIE['test'] = 'test';
    $success = setcookie("test","test",  strtotime("+1 month"),"/");
    var_dump($success);
    echo "a";
}
else{
    var_dump($_COOKIE);
    echo "b";
}
ob_end_flush();

Result: "bool(false) a". So setcookie returns false. Why? That's my question. It works on localhost, but I also uploaded the script to a website of a friend of mine and it works. His and mine website are hosted by the same company, but probably on a different server. He ran the script on his pc too, went exactly the same as with me, so it isn't one of my pc's settings.

/tl;dr/ setcookie returns false on the server, but works (returns true) on localhost and another website.

Jongware
  • 22,200
  • 8
  • 54
  • 100
FishBrainn
  • 11
  • 3
  • 1
    Move `error_reporting(E_ALL);` to be _first_ and also add `ini_set('display_errors', 1);` Cookie and session problems are very often related to the [Headers already sent](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) error, which you may not be seeing the error reports from. – Michael Berkowski Oct 27 '15 at 12:59
  • 1
    according to the doc the only case where it returns false is `If output exists prior to calling this function, setcookie() will fail and return FALSE` - have you investigated in this direction ? – birdspider Oct 27 '15 at 13:00
  • After moving error_reporting to the first line and adding ini_set, it suddenly worked. The 'real' code does not work yet, but now I at least now where to look. But should ob_start "prevent" headers being sent before running ob_end_flush? Or is this my misinterpretation? – FishBrainn Oct 27 '15 at 13:06

0 Answers0