2

我读到可以在将 HTML 内容从 PHP 脚本发送到 Web 服务器后设置 cookie 值。

但是,在处理这个问题时,我无法像我希望的那样设置 cookie。有人可以纠正我的差异吗?

4

3 回答 3

4

PHP 只能在发送页面标题时(即在发送内容 - HTML 之前)设置 cookie。这就是HTTP 协议关于 cookie的工作方式,服务器可以向浏览器发送请求以存储 cookie。

如果您希望在页面加载后添加 cookie,您可以通过 JavaScript 来完成。

于 2012-12-11T15:45:00.087 回答
0

您可以设置一个 javascript cookie(使用jQuery 插件有点简单)——或者通过 AJAX 向 php 脚本发送一个值,然后让它设置 cookie。或者最好的选择,您可以在 PHP 级别使用会话而不是 cookie。取决于您的应用程序。

于 2012-12-11T15:44:29.993 回答
-1

I'm guessing you haven't RTM because if you had you would of seen this:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

But more importantly in your case, this:

Note:

You can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script

于 2012-12-11T15:48:34.913 回答