为什么setcookie()函数给我警告。 (包括代码)

时间:2013-08-16 19:12:23

标签: php http web

我正在学习php。我按照PHP手册中的示例代码,但它给了我这个警告。

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

    setcookie("TestCookie", $value);
    setcookie('TestCookie', $value, time() + 3600);
    setcookie("TestCookie", $value, time() + 3600, "/~rasmus/", "example.com",1);
?>
The cookies have been set.
<?php 
    echo 'part 1';
    echo $_COOKIE["TestCookie"];
    echo 'part 2';
    echo $HTTP_COOKIE_VARS['TestCookie'];
    echo 'part 3';
    print_r($_COOKIE);
?>

但输出给了我这个警告。任何人都可以帮忙吗?谢谢!

( ! ) Warning: Cannot modify header information - headers already sent by (output started at /home/tqjustc/Documents/Workspace/PHP/public_html/demo_PHP/demo1.php:2) in /home/tqjustc/Documents/Workspace/PHP/public_html/demo_PHP/demo1.php on line 5
Call Stack
#   Time    Memory  Function    Location
1   0.0001  631440  {main}( )   ../demo1.php:0
2   0.0001  632176  setcookie ( )   ../demo1.php:5

( ! ) Warning: Cannot modify header information - headers already sent by (output started at /home/tqjustc/Documents/Workspace/PHP/public_html/demo_PHP/demo1.php:2) in /home/tqjustc/Documents/Workspace/PHP/public_html/demo_PHP/demo1.php on line 6
Call Stack
#   Time    Memory  Function    Location
1   0.0001  631440  {main}( )   ../demo1.php:0
2   0.0002  632256  setcookie ( )   ../demo1.php:6

( ! ) Warning: Cannot modify header information - headers already sent by (output started at /home/tqjustc/Documents/Workspace/PHP/public_html/demo_PHP/demo1.php:2) in /home/tqjustc/Documents/Workspace/PHP/public_html/demo_PHP/demo1.php on line 7
Call Stack
#   Time    Memory  Function    Location
1   0.0001  631440  {main}( )   ../demo1.php:0
2   0.0002  632624  setcookie ( )   ../demo1.php:7
The cookies have been set. part 1part 2part 3Array ( [PHPSESSID] => 81990884013fa394c95c38b7f6aeac6e ) 

2 个答案:

答案 0 :(得分:0)

setcookie设置响应标头。这意味着,与session_start()一样,您必须在向客户端发送任何数据之前将其称为

有时你会错误地输出一些东西,比如在你的php文件的开头就有一个空格。检查demo1.php上的line 2,它会产生一些输出。

答案 1 :(得分:0)

在执行脚本期间不会修改

$_COOKIE。您使用setcookie()设置的任何Cookie只会在客户的 NEXT 请求中显示在$ _COOKIE中。

除了$ _SESSION之外,当PHP首次启动时,所有的超级全局值都会被设置,然后单独留下。在某些情况下,_SESSION可以在稍后的时间通过session_start()调用进行修改。