search
HomeBackend DevelopmentPHP TutorialHeader cannot be jumped in php

Solution to Warning:cannot modify header information - headers already sent by...

When receiving information, it often prompts: cannot modify header information - headers already sent by (...). In fact, the desired effect has been achieved, but this error message looks unpleasant. I have found many solutions on the Internet. The solution obtained through comprehensive use is

1. Add ob_start() to the PHP tag at the top of the page;

2. In the returned Add ob_end_flush();

This way you can block the reality of the error message

Also transfer other people's methods, maybe it will be effective in other situations

If you got this message: "Warning: Cannot modify header information - headers already sent by ...."
If you see this warning when executing the php program: "Warning: Cannot modify header information - headers already sent by ...."

Few notes based on the following user posts:
There are several solutions:

1. Blank lines:
Make sure no blank line after of the calling php script.
Check if there is php... ?> There is no blank line after it, especially include or require files. Many problems are caused by these blank lines.

2. Use exit statement (use exit to solve):
Use exit after header statement seems to help some people
Add exit() after header;
header ("Location: xxx");
exit();

3. PHP has this annoying problem, if your HTML goes before any PHP code or any header modification before redirecting to certain page, it'll said "Warning: Cannot modify header information - headers already sent by ...." Basically anytime you output to browser, the header is set and cannot be modified. So two ways to get around the problem:

3a. Use JavaScript (solve with Javascript):

<? echo "<script> self.location(\"file.php\");</script>"; ?>

Since it's a script, it won't modify the header until execution of Javascript.
You can use Javascript to replace header. But I did not execute the above code successfully... In addition, it should be noted that using this method requires the browser to support Javascript.

3b. Use output buffering (solve with output caching):

<?php ob_start(); ?> 
... HTML codes ... 
<?php 
... PHP codes ... 
header ("Location: ...."); 
ob_end_flush(); 
?>

This will save the output buffer on server and not output to browser yet, which means you can modify the header all you want until the ob_end_flush() statement. This method is cleaner than the Javascript since Javascript method assumes the browser has Javascript turn on. However, there are overhead to store output buffer on server before output, but with modern hardware I would imagine it won't be that big of deal. Javascript solution would be better if you know for sure your user has Javascript turn on on their browser.

Like the code above, this method caches when generating the page, allowing the header to be output after the header is output. The wish board on this site uses this method to solve the header problem.
When you click on a page in the background management or sometimes in the forum, a
Warning: Cannot modify header information - headers already sent by....
This type of statement will appear at the top of the page. The reason for this is due to the problem of the setcookie statement.

There are some restrictions on the use of cookies, such as:
1. The description of calling setcookie must be placed before the tag
2. Before calling setcookie, echo cannot be used
3. Until the web page is reloaded, Cookies will appear in the program
4. The setcookie function must be sent before any data is output to the browser
5.…
Based on the above restrictions, when executing the setcookie() function, you will often encounter "Undefined index" ", "Cannot modify header information - headers already sent by"... and other problems. The way to solve the error "Cannot modify header information - headers already sent by" is to delay the data output to the browser before generating the cookie. Therefore, you You can add the ob_start(); function at the front of the program. This will solve it.

4.set output_buffering = On in php.ini (Turn on output_buffering in php.ini )
set output_buffering = On will enable output buffering for all files. But this method may slow down your php output. The performance of this method depends on which Web server you're working with, and what kind of scripts you're using.
This method is theoretically the same as the 3b method. However, this method turns on the output caching of all PHP programs, which may affect PHP execution efficiency, depending on the performance of the server and the complexity of the code.

Yesterday I wanted to use PHP to write a piece of code for downloading files. Because I didn’t want to know how to set up the HTTP protocol, I went directly to php.NET to find examples of the header() function. There were many codes, so I directly copied a section,

<?php 
$file = &#39;filetest.txt&#39;;//filetest.txt文件你随便写点东西进去就好了 
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/force-download"); 
header("Content-Type: application/octet-stream"); 
header("Content-Type: application/download"); 
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize(&#39;filetest.txt&#39;)); 
flush(); // this doesn&#39;t really matter.
$fp = fopen($file, "r"); 
while (!feof($fp)) 
{ 
    echo fread($fp, 65536); 
    flush(); // this is essential for large downloads 
}
fclose($fp);
?>

运行了一下发现不行,一直报错:Warning: Cannot modify header information - headers already sent by (output started at E:\xampp\htdocs\test\downloadfile\file_download.php:1) in E:\xampp\htdocs\test\downloadfile\file_download.php on line 3

我很看了很久,文件一开始就直接是header代码了,没任何输出怎么会说已有字符输出了呢?后来上网查到别人给的提示,才发现,原来我创建文件的时候是直接用记事本存储为UTF8, 原来这样也会出错

----------------以下是引用他人的建议 --------------------

方法一: 
在PHP里Cookie的使用是有一些限制的。 
1、使用setcookie必须在标签之前 
2、使用setcookie之前,不可以使用echo输入内容 
3、直到网页被加载完后,cookie才会出现 
4、setcookie必须放到任何资料输出浏览器前,才送出 
..... 
由于上面的限制,在使用setcookie()函数时,学会遇到 "Undefined index"、"Cannot modify header information - headers already sent by"…等问题,解决办法是在输出内容之前,产生cookie,可以在程序的最上方加入函数 ob_start();

ob_start :打开输出缓冲区 
函数格式:void ob_start(void) 
说明:当缓冲区激活时,所有来自PHP程序的非文件头信息均不会发送,而是保存在内部缓冲区。为了输出缓冲区的内容,可以使用 ob_end_flush()或flush()输出缓冲区的内容。


方法二: 
解 决Warning: Cannot modify header information - headers already sent by ...... 前几天装了个php的大头贴系统测试,发现报错Warning: Cannot modify header information - headers already sent by ......
今天又装openads,还是出现这个问题。怒了。上网找了半天,有人说要在文件开头写上 
ob_start(); 
失败。 
后来打开 php.ini 然后把 output_buffering 设为 on 。重起appache,OK。看来这才是解决办法。

特别注意:(我就是看了这个才解决问题的) 
如果使用utf-8编码,一定要去掉UTF-8中的BOM,这都是因为utf-8编码文件含有的bom原因,而php4,5都是不支持bom的。去掉 bom,可以用Notepad++打开转换一下。(我就是看了这个才解决问题的)

用PHP的ob_start(); 控制您的浏览器cache 。我另外单独转载了一篇文章关于用PHP的ob_start();控制您的浏览器cache的文章 

更多php中header无法跳转相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.