无法修改标头信息

Oye*_*yed 0 php

可能重复:
PHP已发送的标头

我的问题是我有一个带有函数的类,我得到了;

Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/inc/class.php:105) in /home/user/public_html/inc/facebook/login.php on line 21
Run Code Online (Sandbox Code Playgroud)

当我正在使用它的页面重定向用户头(); 标签.这堂课是;

class mysql {
private $user;
private $pass;
private $db;

public function __construct($user1, $pass1, $db1) {
    $this->user = $user1;
    $this->pass = $pass1;
    $this->db = $db1;
    $this->connect();
}

public function connect() {
    $this->connection = mysql_connect('localhost', $this->user, $this->pass);
    $select = mysql_select_db($this->db, $this->connection);
}

public function query($x) {
    return mysql_query($x);
}

public function fetch($x) {
    return mysql_fetch_array($x);
}

public function num($x) {
    return mysql_num_rows($x);
}
}
Run Code Online (Sandbox Code Playgroud)

105号线是;

return mysql_fetch_array($x);
Run Code Online (Sandbox Code Playgroud)

尝试执行标头重定向的文件只是在页面顶部包含此文件,并将标题降低.

提前致谢.

Tre*_*non 8

什么是触发此错误?

在调用标题函数之前,某些代码已经输出到"屏幕"时会触发此错误.在输出任何内容之前必须设置标题.

请参阅header()PHP手册页面中的说明:

请记住,在发送任何实际输出之前,必须通过普通HTML标记,文件中的空行或PHP来调用header().使用include()或require(),函数或其他文件访问函数读取代码是一个非常常见的错误,并且在调用header()之前输出空格或空行.使用单个PHP/HTML文件时存在同样的问题.

我没有输出任何东西,所以给出了什么?

我会说你的代码在某处产生错误.尝试设置:

ini_set('display_errors', true);
ini_set('error_reporting', ~0);
Run Code Online (Sandbox Code Playgroud)

在index.php文件中作为第一组命令.

另一种可能性是某处某处输出空格或行返回字符.你不能有任何的输出任何类型的调用之前header()函数.

可能的解决方案

有两种方法可以解决这个问题.

  1. 在设置标题之前,使用输出缓冲来捕获可能被回显的任何内容
  2. 停止代码过早输出任何东西,虽然这有点脆弱

选项1

要实现解决方案1,您可以ob_start()在代码的最开头(通常在引导文件或index.php的顶部)进行调用.

然后,一旦所有逻辑完成并且您准备输出,您将调用ob_end_flush()输出缓冲区中的所有内容.通常这将位于index.php或bootstrap文件的最后.

选项2

Zend Framework在其编码指南中有以下内容,以帮助减轻新线路和空间的意外输出.请参阅http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html#coding-standard.php-file-formatting.general:

对于仅包含PHP代码的文件,绝不允许使用结束标记("?>").PHP不需要它,省略它可以防止意外地将尾随空白空间注入响应中.