When using cookies yesterday, the page reported an error: php Cannot modify header information-headers already sent by. Let me summarize the solutions to the error.
Code
代码如下 | 复制代码 |
ob_start(); setcookie("username","宋岩宾",time()+3600); echo "the username is:".$HTTP_COOKIE_VARS["username"]."n"; echo "the username is:".$_COOKIE["username"]."n"; print_r($_COOKIE); ?> |
Warning: Cannot modify header information - headers already sent by Cause of error
I added it at the head of the php program,
header("cache-control:no-cache,must-revalidate");
Cause Analysis
There are some restrictions on the use of cookies in PHP.
1. Use setcookie must be before the tag
2. Before using setcookie, you cannot use echo to input content
3. The cookie will not appear until the web page is loaded
4. setcookie must be placed before any data is output to the browser before sending
.....
Due to the above limitations, when using the setcookie() function, we will encounter problems such as "Undefined index", "Cannot modify header information - headers already sent by"... etc. The solution is to generate a cookie before outputting the content
Solution
1 Add ob_start();
to the php tag at the top of the page2 Add ob_end_flush();
under the returned informationThis way you can block the reality of misinformation
But some friends said that the above method did not work. Later, I opened php.ini and set output_buffering to on. Restart appache, OK. It seems this is the solution.
In addition, some friends said that it is an encoding problem, which can be solved as long as the converted document has UFT-8, which will not be introduced here.