Link to home
Start Free TrialLog in
Avatar of stephaneeybert
stephaneeybert

asked on

Conflict between SetCookie() and include ?

Dear All,

I would like to know why I cannot use the SetCookie() function after having used the include directive in a PHP page.

If I use the SetCookie() function before using the include directive, I don't get any error message. But if I use it after, I get a message saying that the html header has already been sent. I know that the SetCookie() function must be used AFTER using the <HEAD> html tag. But how come it also must be used after using the include directive?

Kind Regards
Stephane
Avatar of mrvithan
mrvithan

According to PHP manual, it say cookie must be sent before any other headers are sent. it means this requires you to place calls this function before any <HTML> or <HEAD> tag.

I think you can place it after <HTML> might be a bug.... It get the same error with session on PHP4
the setcookie() function (session() equally) adds information to the http header that is sent before _any_ content. This is like typing a command on your command line, after you've pressed enter, there is no way of altering the parameters. So you cannot send the cookie information after the <header> tag. Maybe there is a confusion here between the HTML <HEADER> tag and the HTTP header containing the cookie
Be especially aware of any whitespaces and newlines outside the <?php ?>tags

maf
Avatar of stephaneeybert

ASKER

Here is what I do:

<?php

include myfile.inc

?>

<?php

setcookie(...);

print ("<HTML><HEAD><BODY>");
....

?>

And it does not work.

If I remove the include directive, then it works.

Cheers
Stephane
What is it with the white spaces and new lines outside of the php tags?
What should I do?
Cheers
Stephane
have a look at the line between the ?> an the <?

                      include myfile.inc

                      ?>

                      <?php

                      setcookie(...);

try

<?
 include myfile.inc

// no ?> <? here

setcookie(...);

?>

you may not output any characters (that's what the line actually does) before setcookie()

maf
Hi maf,
It was white spaces after the ?> in the included files that posed problem. I removed them, and now it's fine. You got your points.
Thanks
Stephane
ASKER CERTIFIED SOLUTION
Avatar of mafweb
mafweb

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial