setcookie,无法修改标题信息 - 标题已发送 [英] setcookie, Cannot modify header information - headers already sent

查看:29
本文介绍了setcookie,无法修改标题信息 - 标题已发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PHP 新手,我刚刚练习了 PHP setcookie() 失败了.

I am new to PHP, I practised PHP setcookie() just now and failed.

http://localhost/test/index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>

    </head>
    <body>
     <?php
     $value = 'something from somewhere';

     setcookie("TestCookie", $value);
     ?>
    </body>
</html>

http://localhost/test/view.php

<?php
 // I plan to view the cookie value via view.php
 echo $_COOKIE["TestCookie"];

?>

但是我运行index.php失败了,IE这样的警告.

But I failed to run index.php, IE warning like this.

Warning: Cannot modify header information - headers already sent by (output started at C:xampphtdocs	estindex.php:9) in C:xampphtdocs	estindex.php on line 12

毫无疑问,我启用了我的 IE 6 cookie.

I enabled my IE 6 cookie no doubt.

我上面的程序有什么问题吗?谢谢.

Is there anything wrong on my procedure above? Thank you.

使用了 WinXP 操作系统和 XAMPP 1.7.3.

推荐答案

警告很清楚.

警告:无法修改标头信息 - 标头已由(输出开始于 C:xampphtdocs estindex.php:9)在 C:xampphtdocs estindex.php 中第 12 行发送

Warning: Cannot modify header information - headers already sent by (output started at C:xampphtdocs estindex.php:9) in C:xampphtdocs estindex.php on line 12

Cookie 在 HTTP 响应标头中发送.由于 HTML 内容已经开始,您无法返回标题并添加 cookie.

Cookies are sent in the HTTP response header. Since the HTML content already started, you cannot go back to the header and add the cookie.

来自http://php.net/setcookie:

setcookie() 定义了一个与其余 HTTP 标头一起发送的 cookie.与其他标头一样,cookie 必须在之前从脚本的任何输出发送(这是协议限制).这要求您在任何输出之前调用此函数,包括 标签以及任何空格.

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 <html> and <head> tags as well as any whitespace.

在任何 HTML 出现之前移动 setcookie 语句:

Move that setcookie statement before any HTML appears:

<?php
 $value = 'something from somewhere';

 setcookie("TestCookie", $value);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
....

这篇关于setcookie,无法修改标题信息 - 标题已发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆