setcookie error in php

1

Why this simple code shows error assigning the cookie as if something had already been written before setting the cookie

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<?php
$value = 'cualquier cosa';
setcookie("TestCookie", $value);
?>
</body>
</html>

The warning that xdebug shows is:

  

Warning: Can not modify header information - headers already sent by   (output started at   /srv/http/codiad/workspace/aulamentor/php/2016/temp.php:8) in   /srv/http/codiad/workspace/aulamentor/php/2016/temp.php on line 10

    
asked by Theasker 20.06.2016 в 22:44
source

2 answers

0

As you can see in the documentation of setcookie , the function will place the cookie for that is added as part of the headers of the content of the response. In this case, the code you have is already part of the response, and the setcookie method is trying to add information in a response that is already written, thus the error message is completely valid.

Be sure to create the cookies before generating the server-side response, that is, before generating any HTML fragment.

    
answered by 20.06.2016 / 22:49
source
0

setcookie must be called before the generated output, in this case the html code.

Taken from the PHP documentation:

  

setcookie () defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before the script generates any output (it is a protocol restriction). This implies that calls to this function are placed before any output is generated, including the < html > and < head > just like any blank space.

    
answered by 20.06.2016 в 22:48