1

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.

2
  • 3
    How are you setting the session? You should provide your code so we can see what's going on. Commented Dec 10, 2009 at 4:23
  • Can you post the code you're using? Commented Dec 10, 2009 at 4:23

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.