php header函式的詳解

來源:酷知科普網 2.14W

header函式在php中是傳送一些頭部資訊的, 我們可以直接使用它來做301跳轉等,下面我來總結關於header函式用法與一些常用見問題解決方法。
傳送一個原始 HTTP 標頭[Http Header]到客戶端。標頭 (header) 是伺服器以 HTTP 協義傳 HTML 資料到瀏覽器前所送出的字串,在標頭與 HTML 檔案之間尚需空一行分隔.

php header函式的詳解

操作方法

(01)1.重定向.檢視原始碼列印幫助Header("Location: ");exit; //在每個重定向之後都必須加上“exit”,避免發生錯誤後,繼續執行。

(02)2.禁止頁面在IE中快取檢視原始碼列印幫助header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );header( 'Cache-Control: no-store, no-cache, must-revalidate' );header( 'Cache-Control: post-check=0, pre-check=0', false );header( 'Pragma: no-cache' ); //相容http1.0和https

(03)3.實現檔案下載檢視原始碼列印幫助header('Content-Type: application/octet-stream');//設定內容型別header('Content-Disposition: attachment; filename=""'); //設定MIME使用者作為附件下載 如果將attachment換成inline意思為線上開啟header('Content-Transfer-Encoding: binary');//設定傳輸方式header('Content-Length: 'size(''));//設定內容長度readfile('');//讀取需要下載的檔案

(04)4. 向瀏覽器傳送Status標頭header(”Status: 404 Not Found”);但是我發現實際上瀏覽器返回的響應卻是:檢視原始碼列印幫助// okheader(‘HTTP/1.1 200 OK’);//設定一個404頭:header(‘HTTP/1.1 404 Not Found’);//設定地址被永久的重定向header(‘HTTP/1.1 301 Moved Permanently’);HTTP/1.x 200 OKDate: Thu, 03 Aug 2006 07:49:11 GMTServer: Apache/2.0.55 (Win32) PHP/5.0.5X-Powered-By: PHP/5.0.5Status: 404 Not FoundContent-Length: 0Keep-Alive: timeout=15, max=98Connection: Keep-AliveContent-Type: text/html

(05)注意事項有以下幾點tion和”:”之間不能有空格,否則會出現錯誤(註釋:我剛測試了,在我本地環境下,沒有跳轉頁面,但是也沒有報錯,不清楚什麼原因);在用header前不能有任何的輸出(註釋:這點大家都知道的,如果header之前有任何的輸出,包括空白,就會出現header already sent by xxx的錯誤);header 後面的東西還會執行的;

熱門標籤