views:

82

answers:

3

Hi all, how can I set cookies in the middle of a document, without incurring a 'headers already sent' error? What I'm trying to do is make a log out script (the log in cookie setting works...so odd. Is it because it's enclosed in an if statement?) however I've already echoed the page title and some other stuff at the top of the page, before I've made this logout happen.

Thanks!

+5  A: 

Try to decompose your application in two parts : First, you unset the cookie, then you redirect user on the result page. It's a commo way to work.

Also try to use a framework in your development, it will improve your skills and the maintenability of your code.

Brice Favre
+1 for recompose. Setting cookies in the middle of *output* (not middle of document, of course) is a nonsense.
Col. Shrapnel
I'll look into a framework :).
Sam
+4  A: 

The easiest way is to use output buffering to stop PHP from sending data to the client until you're ready

<?php
ob_start();
// your code
ob_end_flush();
?>

Output buffering stores all outputted data until the buffer is flushed, and then sends it all at once, so any echos after the start will remain buffered until the end_flush and then sent

Michael Mrozek
Thankyou thankyou thankyou =D!
Sam
+1  A: 

Cookies are sent in the headers, which are sent before anything else is sent. Therefore, if you have actually 'echoed' something to the client (browser), your headers have also been sent.

That said, you can buffer your output and send it all once all the code has been run (ob_start() and ob_end_flush())

Lauri Lehtinen