PHP Hint Cannot modify header information headers already sent by Solution
- 2021-07-18 07:37:44
- OfStack
This paper describes the solution of PHP, Cannot, modify, header, information-headers, already, sent, by, which is often encountered in the process of PHP programming. This paper analyzes the solutions in the form of examples. Share it for your reference. The specific methods are as follows:
Let's take a look at this code:
<?php
ob_start();
setcookie("username","test",time()+3600);
echo "the username is:".$HTTP_COOKIE_VARS["username"]."\n";
echo "the username is:".$_COOKIE["username"]."\n";
print_r($_COOKIE);
?>
Prompt Warning when accessing the PHP file: Cannot modify header information-headers already sent by
Cause of error:
The reason is that header ("content-type: text/html; charset=utf-8 "); After that, the above error appears on the page.
Because header ('Content-Type: text/html; charset= UTF-8 '); You can't have any output before sending the header, and you can't have any spaces either. You need to remove the spaces before header (...) or other output things. If there are other include files on it, you also need to check whether there are outputs in other files.
I looked up some information on the Internet and said that there was something wrong with the configuration of my php. ini. I found that output_buffering in php. ini defaulted to off, and changed it to on or any one number, but I tried no result.
The setcookie function must send any data before it is output to the browser
Based on the above limitations, when running setcookie () function, we often encounter problems such as "Undefined index", "Cannot modify header information-headers already sent by", etc. The solution to the error of "Cannot modify information-headers already ES80by" is to delay the data output to the browser before generating cookie, so you can add ob_start () at the front of the program.
ob_start () function is used to open the buffer. For example, if there is output before header () function, including carriage return\ space\ line feed\ there will be an error of "ES90had all ready send by". At this time, you can open the buffer first with ob_start (). The data block of PHP code and echo () output will enter the buffer without immediate output!
The problem is solved by the following methods:
// In header() Before
ob_start(); // Open buffer
echo \"Hellon\"; // Output
header("location:index.php"); // Redirect the browser to index.php
ob_end_flush();// Output all the contents to the browser
?>
I hope this article is helpful to everyone's study of PHP programming.