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>) {
    setcookie('MY_USER',$_POST['username'],time()+3600);
} else if(isset($_COOKIE['MY_USER'] && isset($_POST['logout'])) {
    setcookie('MY_USER',$_POST['username'],time()-3600);
}

<later>
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,

sj

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
http://php.net/manual/en/function.setcookie.php

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

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

Kind Regards

:slight_smile:

or…

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.
:wink:

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.

sj

Sponsor our Newsletter | Privacy Policy | Terms of Service