cookie help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

cookie help

Post by Sevengraff »

when i use this:

Code: Select all

<?PHP 
setcookie("page", $SCRIPT_NAME,time()+120);
?>


I get this:

Warning: Cannot add header information - headers already sent by (output started at /usr/local/psa/home/vhosts/abeta.anime-honor.com/httpdocs/function.php:168) in /usr/local/psa/home/vhosts/abeta.anime-honor.com/httpdocs/add_ffa.inc on line 12

what am i doing wrong? Ive never used cookies before.
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post by gnu2php »

It's because cookies are sent in HTTP "headers," and these headers are always sent before the HTML is. So you need to set your cookie before anything is outputted.

Or you could use "output buffering," to prevent anything from being outputted:

Code: Select all

<?php

ob_start();
echo "Hello\n";

setcookie ("cookiename", "cookiedata");

ob_end_flush();

?>
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

Post by Sevengraff »

thanks, i'll try that!
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

Post by Sevengraff »

no, i still get the same error, what do you mean by "Se your cookie before anything is outputted"?
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post by gnu2php »

I mean that you need to make sure nothing gets sent to the browser before you set the cookie.

For example:

Code: Select all

<html>  // Cookie won't work (<html> is outputted)

<?php setcookie("cookiename", "cookiedata"); ?>

</html>
But this should work:

Code: Select all

<?php ob_start(); ?>  // Output buffer is enabled

<html>

<?php setcookie ("cookiename", "cookiedata"); ?>

</html>

<?php ob_end_flush(); ?>  // This sends the HTML to the browser
Just make sure <?php ob_start(); ?> is at the very top of the PHP script.
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

Post by Sevengraff »

ohhh. ok thanks!
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

There was of course this sticky at the top of the forum that explains all that:
http://liberty.dnsprotect.com/~devnetwo ... php?t=1157

Mac
Post Reply