-2

I am learning php. I followed the example codes from php manual, but it gives me this warning.

<?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);
?>

but the output gives me this warning. Any one can help ? Thanks !

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

0

setcookie sets a response header. This means that, like session_start(), you must call it before you send any data to the client.

Sometimes you output something by mistake, like having a space at the start of your php file. Check demo1.php on line 2, it produces some output.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
0

$_COOKIE will not be modified during the execution of the script. Any cookies you set with setcookie() will only show up in $_COOKIE on the NEXT request from the client.

Except for $_SESSION, all of the superglobals' values are set when PHP first fires up, and then left alone. _SESSION can be modified by session_start() calls at a later time, under certain conditions.

Marc B
  • 356,200
  • 43
  • 426
  • 500