Search code examples
phpsetcookie

Unable to setcookie in any browser


So I have done a lot of reading on setting cookies and still cannot find what I am doing wrong here. I started with an if statement to include another script but it soon became clear the cookie wasn't setting so I simplified it and made it just to echo so I could see if it was setting. Its not. I am including it above the <html>.

I am setting the cookie and then refreshing and no matter how many times I refresh it is still returning a NULL result in the echo command.

  • The setcookie is above all of my html, cookies can't be set after any output??
  • The value is set, and domain.
  • All browsers have cookies enabled, and friends have tested this for me so its not local.
  • Its not the server, I asked my host.
  • I have even copy/pasted code from PHP manual to no avail.
  • And of course checked SO a few mil times.

    $var='Something';
    setcookie ("Name", "$var", time()+3600, '/', 'website.com');
    echo $_COOKIE["Name"];
    var_dump($_COOKIE["Name"]);
    var_dump ($HTTP_COOKIE_VARS); 
    

echo returning NULL and var_dump returning Array(0)

I am going mad, is there something wrong in my code, what am I missing?


Solution

  • The most frequent problem with setting cookies (or any other header) is, that it has to be set before you send first output character. There may be an invisible character before your script (like BOM or whitespace). If you use includes, thare may be a whitespace after the closing tag of your included script.