views:

169

answers:

2

Can't I set session and cookie in same PHP file?

I get an error message if I set the cookie after I've set session telling me that the header is already sent.

If I set session after cookie I get nothing but it seems not to work well.

+1  A: 

You can always set session on cookies on a same page. However you should always start a session or set a cookie before generating any output.The error message you are getting is because you are echoing out a block of HTML or string before starting a session (i.e. session_start()) or setting a cookie (i.e. setcookie()).

For a more detailed explanation, see 'description' sections in: http://php.net/manual/en/function.setcookie.php

and 'Notes' section in: http://php.net/manual/en/function.session-start.php

Kailash Badu
so should i use setcookie() first or use session_start() first. do they interfere with each other?
never_had_a_name
I guess it doesn't matter but logically session_start() should come first. setcookie() will implicitly start a session anyway.
Kailash Badu
+2  A: 

The short answer is yes - you can set SESSION and COOKIE data in the same PHP file.

The longer answer:

  • Cookie data is sent in the header of the page.
  • You can not set cookies after you have sent the headers to the client.
  • Headers will be sent as soon as you start outputting any data to the client (ie: the browser).

It is likely that in your case, you have sent the header and/or started outputting data to the client in the same place you are setting SESSION data.

See the PHP manual: Cookies for more details. In particular the quote of:

"Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers."

If you need further help - try inserting your sample code/page that you are having issues with.

catchdave