先看两个PHP文件,A.php ?> 后面有空行
1
2
3
4
5
6
7
8
9
class A
{
const A_TEST = 'A';
}
.
B.php 引入 A.php,在输出之前有header等函数调用
1
2
3
4
5require_once(__DIR__ . '/A.php');
header('HTTP/1.1 404 Not Found');
header('status:404 Not Found');
echo A::A_TEST;
此时执行B.php报错如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
PHP Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\demo\short1.php:10) in D:\xampp\htdocs\demo\short2.php on line 5
PHP Stack trace:
PHP 1. {main}() D:\xampp\htdocs\demo\short2.php:0
PHP 2. header() D:\xampp\htdocs\demo\short2.php:5
Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\demo\short1.php:10) in D:\xampp\htdocs\demo\short2.php on line 5
Call Stack:
0.0003 375864 1. {main}() D:\xampp\htdocs\demo\short2.php:0
0.0006 376280 2. header() D:\xampp\htdocs\demo\short2.php:5
PHP Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\demo\short1.php:10) in D:\xampp\htdocs\demo\short2.php on line 6
PHP Stack trace:
PHP 1. {main}() D:\xampp\htdocs\demo\short2.php:0
PHP 2. header() D:\xampp\htdocs\demo\short2.php:6
Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\demo\short1.php:10) in D:\xampp\htdocs\demo\short2.php on line 6
Call Stack:
0.0003 375864 1. {main}() D:\xampp\htdocs\demo\short2.php:0
0.0013 376280 2. header() D:\xampp\htdocs\demo\short2.php:6
short1[Finished in 0.2s]
这是因为在调用header函数之前已经有空行输出了,而这些函数在调用前是不允许有输出的,所以如果文件是纯PHP代码,那么建议去掉PHP文件的闭合标签,这样可以避免在PHP文件结束标记之后输入空格或者空行之后,输出无意义的空格或者空行。
header() 用于发送原生的 HTTP 头。header() 必须在任何实际输出之前调用,不管是普通的 HTML 标签,还是文件或 PHP 输出的空行,空格。这是个常见的错误,在通过include,require,或者其访问其他文件里面的函数的时候,如果在header()被调用之前,其中有空格或者空行。 同样的问题也存在于单独的 PHP/HTML 文件中。