开发者

Session and cookie in same PHP file?

开发者 https://www.devze.com 2022-12-13 20:25 出处:网络
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.

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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消