Home Backend Development PHP Tutorial Header cannot be jumped in php

Header cannot be jumped in php

May 14, 2018 pm 03:53 PM

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 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>"; ?>
Copy after login

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(); 
?>
Copy after login

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);
?>
Copy after login

运行了一下发现不行,一直报错: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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles