2

The problem is that I can't set a cookie from PHP. I've tried to google the problem and searching here on stackoverflow, but none of the solutions work.

I've tried:

setcookie('user_id', $row['user_id'], time() + ( 60 * 60 * 8), '/', '127.0.0.1');
setcookie('user_id', $row['user_id'], false, '/', false);
setcookie('user_id', $row['user_id'], time() + ( 60 * 60 * 8), '/', false);
setcookie('user_id', $row['user_id'], time() + ( 60 * 60 * 8), '/', '');

The browser I'm using is Firefox 12 and Chrome 19 on an Apache server.

Thanks for your help.

EDIT: There seems to be a problem with my database when I fetch data to put in my cookies, so nevermind;) thanks for your time!

ptf
  • 3,210
  • 8
  • 34
  • 67
  • 2
    How do you know that it doesn't work? – flowfree May 24 '12 at 15:28
  • Did you get an error or how do you know it doesn't work? – Oscar Jara May 24 '12 at 15:29
  • After I redirect and try to use the cookie, it isn't set. isset returns false, and nothing works as it is supposed to if the cookies were working. – ptf May 24 '12 at 15:44
  • Probably the same problem reported here: http://stackoverflow.com/questions/390219/why-wont-asp-net-create-cookies-in-localhost – Cacovsky May 24 '12 at 15:51
  • Have you ensured that there is no output before those commands. The HTTP headers need to be sent first and that includes any output including encoding characters. The `setcookie` will be ignored. Your best bet is to use live HTTP headers for Firefox to see what is going on. – Ed Heal May 24 '12 at 15:30
  • I have a header('Location: ' ... ); after this, and it redirects successfully. I'll try the HTTP headers:) – ptf May 24 '12 at 15:41
  • @kjelelokk - Use Firefox add on HTTP live headers. Then use `telnet` and type in exactly what is being sent to the server. You will then get the output from the server and you will be able to find out what is happening. – Ed Heal May 24 '12 at 15:44

1 Answers1

2

Are you sure there is no output before that code? All echos and all includes including something that is not completely PHP code are considered output.

The reason you cannot output anything before a setcookie() call is quite simple. To set a cookie, the server must send an header instruction to the browser. That header cannot be sent if content body is already printed out.

You can change your code to put that calls before any output, or you can simple put an ob_start() at the beginning of your code. That function cause PHP to buffer all the output and send it only one when script ends.

lorenzo-s
  • 16,603
  • 15
  • 54
  • 86