Page 1 of 1

setcookie() header issues

Posted: Thu Sep 11, 2003 10:06 am
by planethax
[Admin Edit: Moved from the headers sticky: viewtopic.php?t=1157]

ok the below code works fine on its own page loginbox.php
but I need it as an include on other pages, but I get the header error unless I remove the set cookie line (third line)
How can I go about this? any ideas?

Code: Select all

<?php
include("config.php");
setcookie("page","$PHP_SELF",time()+155555);
if($loged=='yes')
{
?>
<table width="100%" border="0">
<tr><td>
<?php echo $lang[hello] ?> <?php echo $name ?>.
<?php echo "$lang[logedas] $username"; ?> 
</td><td>
<?php include("new_messages.php"); ?><BR>
<a href="editaccount.php"><?php echo $lang[editaccount] ?></a><BR>
<a href="changepass.php"><?php echo $lang[changepass] ?></a><BR>
<a href="logout.php"><?php echo $lang[logout] ?></a>
</td></tr></table>
<?
}
else
{
?>
<table width="100%" border="0">
<tr><td>
<form action="login.php" method="post">
<?php echo $lang[username] ?> : <input type="text" name="username"> <BR>
<?php echo $lang[password] ?> : <input type="password" name="password">
<BR><input type="submit" value="<?php echo $lang[loginbutton] ?>">
</td><td><a href="register.php"><?php echo $lang[register] ?></a> | <a href="lostpass.php"><?php echo $lang[forgottenpassword] ?></a>
</form>
</td></tr></table>
<?
}
?>

Posted: Thu Sep 11, 2003 7:24 pm
by McGruff
setcookie() is itself a kind of header call so the same rules as for header() apply, ie no browser output prior to the header call.

If as you say this script works on its own but not when it's included, check the calling script for any output (including whitespace as explained in this thread) prior to the include.

PS: I changed the [ code ] tags to [ php ] to make it easier to read.

Posted: Thu Sep 11, 2003 8:54 pm
by planethax
so If I have this right, any page I have include loginbox.php
if I put
<?php
ob_start();
?>
at the start befor <hmtl> it will be ok?

Posted: Fri Sep 12, 2003 7:28 am
by Bennettman
Not recommended since you don't really want to put the whole page in a buffer before outputting it.

The way I use is to buffer then include the page you want included right at the start of the page, and move whatever HTML comes from the page to a variable that can be put in wherever you'd include it normally. That way all the headers get taken care of, and a variable with the content is generally easier to take care of than an include.

Code: Select all

<?php

ob_start(); // start buffering
include "loginbox.php"; // include file
$content = ob_get_contents(); // set the variable
ob_end_clean(); // empty the buffer

?>

--Start rest of code in the including page--

<?php echo $content; // put loginbox.php in ?>

--Rest of code--