header函數(shù)在php中是發(fā)前一些頭部信息的,如果我們可以直接使用它來(lái)做301跳轉(zhuǎn)等,下面我來(lái)總結(jié)關(guān)于header函數(shù)用法與一些常用見(jiàn)問(wèn)題解決方法。

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

例1,代碼如下:

  1. <?PHP 
  2. Header(“Location: http://www.phpfensi.com”;); 
  3. exit//在每個(gè)重定向之后都必須加上“exit”,避免發(fā)生錯(cuò)誤后,繼續(xù)執(zhí)行。 
  4. ?> 

禁止頁(yè)面在IE中緩存,代碼如下:

  1. <?PHP 
  2. header( ‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’ ); 
  3. header( ‘Last-Modified: ‘ . gmdate( ‘D, d M Y H:i:s’ ) . ‘ GMT’ ); 
  4. header( ‘Cache-Control: no-store, no-cache, must-revalidate’ ); 
  5. header( ‘Cache-Control: post-check=0, pre-check=0′, false ); 
  6. header( ‘Pragma: no-cache’ ); //兼容http1.0和https 
  7. ?> 
  8. //CacheControl = no-cache 
  9. //Pragma=no-cache 
  10. //Expires = -1 

實(shí)現(xiàn)文件下載,代碼如下:

  1. header('Content-Type: application/octet-stream');//設(shè)置內(nèi)容類(lèi)型 
  2. header('Content-Disposition: attachment; filename="example.zip"'); //設(shè)置MIME用戶作為附件下載 如果將attachment換成inline意思為在線打開(kāi) 
  3. header('Content-Transfer-Encoding: binary');//設(shè)置傳輸方式 
  4. header('Content-Length: '.filesize('example.zip'));//設(shè)置內(nèi)容長(zhǎng)度 
  5. // load the file to send: 
  6. readfile('example.zip');//讀取需要下載的文件 

php的函數(shù)header()可以向?yàn)g覽器發(fā)送Status標(biāo)頭,代碼如下:

header(”Status: 404 Not Found”)。

但是我發(fā)現(xiàn)實(shí)際上瀏覽器返回的響應(yīng)卻是如下代碼:

  1. // ok 
  2. header(‘HTTP/1.1 200 OK’); 
  3. //設(shè)置一個(gè)404頭: 
  4. header(‘HTTP/1.1 404 Not Found’); 
  5. //設(shè)置地址被永久的重定向 
  6. header(‘HTTP/1.1 301 Moved Permanently’); 
  7. HTTP/1.x 200 OK 
  8. Date: Thu, 03 Aug 2006 07:49:11 GMT 
  9. Server: Apache/2.0.55 (Win32) PHP/5.0.5 
  10. X-Powered-By: PHP/5.0.5 
  11. Status: 404 Not Found 
  12. //開(kāi)源軟件:phpfensi.com 
  13. Content-Length: 0 
  14. Keep-Alive: timeout=15, max=98 
  15. Connection: Keep-Alive 
  16. Content-Type: text/html 

注意事項(xiàng)有以下幾點(diǎn):

?Location和":"之間不能有空格,否則會(huì)出現(xiàn)錯(cuò)誤(注釋,我剛測(cè)試了,在我本地環(huán)境下,沒(méi)有跳轉(zhuǎn)頁(yè)面,但是也沒(méi)有報(bào)錯(cuò),不清楚什么原因);

?在用header前不能有任何的輸出(注釋,這點(diǎn)大家都知道的,如果header之前有任何的輸出,包括空白,就會(huì)出現(xiàn)header already sent by xxx的錯(cuò)誤);

?header 后面的東西還會(huì)執(zhí)行的.

轉(zhuǎn)載請(qǐng)注明來(lái)源:php header函數(shù)的詳解

  哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業(yè)制作大氣、美觀的優(yōu)秀網(wǎng)站,并且能夠搭建符合百度排名規(guī)范的網(wǎng)站基底,使您的網(wǎng)站無(wú)需額外費(fèi)用,即可穩(wěn)步提升排名至首頁(yè)。歡迎體驗(yàn)最佳的哈爾濱網(wǎng)站建設(shè)