php header函數常見用途

header函數在php中是發送一些頭部信息的, 我們可以直接使用它來做301跳轉等,下面我來總結關於header函數用法與一些常用見問題解決方法。 

發送一個原始 HTTP 標頭[Http Header]到客戶端。標頭 (header) 是服務器以 HTTP 協義傳 HTML 資料到瀏覽器前所送出的字串,在標頭與 HTML 文件之間尚需空一行分隔. 

1.重定向. 

Header("Location: http://www.mobiletrain.org"); 
exit; //在每個重定向之後都必須加上“exit”,避免發生錯誤後,繼續執行。 
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 
3.實現文件下載 

header('Content-Type: application/octet-stream');//設置內容類型 
header('Content-Disposition: attachment; filename="example.zip"'); //設置MIME用戶作爲附件下載 如果將attachment換成inline意思爲在線打開 
header('Content-Transfer-Encoding: binary');//設置傳輸方式 
header('Content-Length: '.filesize('example.zip'));//設置內容長度 
readfile('example.zip');//讀取需要下載的文件 
4. 向瀏覽器發送Status標頭 

header(”Status: 404 Not Found”); 
但是我發現實際上瀏覽器返回的響應卻是: 

// ok 
header(‘HTTP/1.1 200 OK’); 
//設置一個404頭: 
header(‘HTTP/1.1 404 Not Found’); 
//設置地址被永久的重定向 
header(‘HTTP/1.1 301 Moved Permanently’); 

HTTP/1.x 200 OK 
Date: Thu, 03 Aug 2006 07:49:11 GMT 
Server: Apache/2.0.55 (Win32) PHP/5.0.5 
X-Powered-By: PHP/5.0.5 
Status: 404 Not Found 
Content-Length: 0 
Keep-Alive: timeout=15, max=98 
Connection: Keep-Alive 
Content-Type: text/html 
注意事項有以下幾點. 
Location和”:”之間不能有空格,否則會出現錯誤(註釋:我剛測試了,在我本地環境下,沒有跳轉頁面,但是也沒有報錯,不清楚什麼原因); 
在用header前不能有任何的輸出(註釋:這點大家都知道的,如果header之前有任何的輸出,包括空白,就會出現header already sent by xxx的錯誤); 
header 後面的東西還會執行的。

更多技術問題請搜索千鋒PHP,做真實的自己,用良心做教育

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章