Question

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!

Was it helpful?

Solution

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

OTHER TIPS

Try to decompose your application in two parts :

First, you unset the cookie, then you redirect user on the result page. It's a common way to work.

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

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())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top