setcookies() not work in include?

probably a stupid question, but i didn’t see an answer existing that solved it. (saw some that didn’t solve it).

i have a simple login script snippit that works fine using setcookie when run by itself, but when used inside a require_once, it is completely useless.

the gist of the code is this:

<several lines of HTML code first>
if(!isset($_COOKIE['MY_USER']) && isset($_POST['submit']) && <passwordmatch>) {
} else if(isset($_COOKIE['MY_USER'] && isset($_POST['logout'])) {

if(<logged in>) {
    <code for logout>
} else {
    <code for login submit>

all this works fine if i just run this code natively (filename ‘login.php’), but if i include the code within another file (as a sidebar

, say), it does nothing at all.

i’ve tried setting the path argument, domain argument, no luck.

other suggestions include making sure this php code is the absolute first thing in the page, which i guess precludes any use within a require_once (unless it is the first require_once). if that is the case, how do i get my preceding text in there that “sets up” the login?

any thoughts or experiences?

many thanks,


I don’t think you can set cookies after HTML has already been started. So setcookie should be called before or other tags (as far as I’m aware).

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script

QFT, cookie stuff comes after first <?php, before doctype even?

Cookies come infront of everything, not even whitespacing is allowed.

Kind Regards



place this at the top of the file:
[php]<?php ob_start(); ?>[/php]

and place this at the bottom:
[php]<?php ob_end_flush(); ?>[/php]

This will enable output buffering and you can put your cookie anywhere… well almost.

thanks guys, that worked. i didn’t believe it because it had worked fine, even when not at the front of all HTML code. guess it is not strict in its checking.


Sponsor our Newsletter | Privacy Policy | Terms of Service