如何通过 PHP 在文档中设置 cookie?

发布于 2024-09-05 01:15:35 字数 138 浏览 1 评论 0原文

如何在文档中间设置 cookie,而不会出现“标头已发送”错误?我想做的是制作一个注销脚本(登录 cookie 设置有效...太奇怪了。是因为它包含在 if 语句中吗?)但是我已经回显了页面标题和其他一些内容在我进行注销之前,在页面顶部。

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

煮茶煮酒煮时光 2024-09-12 01:15:36

最简单的方法是使用输出缓冲来阻止PHP向客户端发送数据直到准备好

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

输出缓冲存储所有输出的数据,直到刷新缓冲区,然后一次性发送所有数据,因此 start 之后的任何回显都将保持缓冲状态,直到 end_flush 然后发送

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

深巷少女 2024-09-12 01:15:36

尝试将您的应用程序分解为两部分:

首先,取消设置 cookie,然后在结果页面上重定向用户。这是一种常见的工作方式。

还要尝试在开发中使用框架,它将提高您的技能和代码的可维护性。

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.

白衬杉格子梦 2024-09-12 01:15:36

Cookie 在标头中发送,标头在发送其他内容之前发送。因此,如果您实际上已向客户端(浏览器)“回显”某些内容,则您的标头也已发送。

也就是说,您可以缓冲输出并在所有代码运行后将其全部发送(ob_start()ob_end_flush()

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文