2011-05-23 59 views
-1

有沒有什麼更好的辦法來重定向,因爲我得到這個錯誤:重定向用PHP

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\falco\index.php:26) in C:\xampp\htdocs\falco\classes\controller.php on line 306

很多時候使用標題(「位置:?blablabla.php ID = 3」) 是否有任何其他方式重定向並不會得到這個錯誤?或者我做錯了什麼?

謝謝你的時間。

+0

-1:參見[「無法修改標題信息」(HTTP: //http://tinyot.com/modify+header+information%22) – 2011-05-23 00:35:50

+0

[看這裏](http://tinyurl.com/3z4umx9) – Nemoden 2011-05-23 00:50:42

回答

2

您必須在頁面上的任何內容(也是我認爲的空白)之前做標頭更改。因此,將header函數放置在頁面的最頂端。

2

在調用觸發此警告的header()之前,您必須有一些空格或其他輸出。 See the manual

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

+0

@Midas:他不是說「你應該有......「,但」肯定你有...而且是錯的「 – Amadan 2011-05-23 00:31:23

+0

是的,現在我明白了。我刪除了我的評論。 – Midas 2011-05-23 00:32:05

+0

@約翰Kugelman - 謝謝你讓我的答案更清楚。 – 2011-05-23 00:42:19

2

這是一個警告,而不是錯誤。它發生的原因是標題已經發送到瀏覽器。確保在修改頭文件之前,您的PHP文件中沒有任何輸出。這包括echo,print_r以及在初始<?php標記之前的空格。

2

標題需要出現在響應的主體之前。因此,如果你有任何echo'd(包括空白),然後嘗試發送一個頭,它將失敗。

在PHP中留下最後一件東西的輸出。

2

您在打印其他內容後正在打印標題。第一種方法就是你在做什麼,但是你必須等待打印其他東西,直到你知道你是否要重定向。如果在此之前絕對必須打印,則可以使用輸出緩衝功能。 ob_start開始「暫停」打印,然後打印標題,然後撥打ob_end_flush以打印所有被阻止的內容。

第二種方法是將其插入到<head>中,但這也是時間特定的 - 您不能將其插入文檔中的任何位置。

<meta http-equiv="refresh" content="0; url=http://www.example.com/"/> 

第三種方法,隨時隨地堅持這個腳本 - 但這強制客戶端必須允許腳本,或什麼也沒有發生:

<script> location.replace('http://example.com'); </script>