Jump to content

include_once causes "headers already sent by" for setcookie

Recommended Posts


I have strange problem that I did not have before with my host.


I have this php script

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

include_once "./incltest.php";
setcookie('Session', 'val23', 1577840461, '/');



And  the contents of incltest.php is:



The cookie does not set and the message i get it:


Warning: Cannot modify header information - headers already sent by (output started at /incltest.php:3) in test.php on line 7

I figured that if I remove closing tag ?> from php file that I include then *I no longer get this error. So far I've always used closing tags at the end of my php scripts and it has worked that ways. Are there any new php standards out there that now it doesn't work anymore? To me it looks strange to have starting tag <?php at the beginning of my file but not ending tag. Should I now change all my php files or would it be better to set some php ini value?

Share this post

Link to post
Share on other sites

If your script is purely php you do not require closing php tag.

The setcookie() must be set at top before any html or whitespace.

Your code has a empty line-break and then includes another file with empty line-break before setcookie() function result in headers already exist error.


Edited by dsonesuk
  • Like 1

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...