开发者

How to set cookies via PHP in the middle of a document?

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'v开发者_JAVA百科e already echoed the page title and some other stuff at the top of the page, before I've made this logout happen.

Thanks!


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜