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,代碼如下:
- <?PHP
- Header(“Location: http://www.phpfensi.com”;);
- exit; //在每個(gè)重定向之后都必須加上“exit”,避免發(fā)生錯(cuò)誤后,繼續(xù)執(zhí)行。
- ?>
禁止頁(yè)面在IE中緩存,代碼如下:
- <?PHP
- 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
- ?>
- //CacheControl = no-cache
- //Pragma=no-cache
- //Expires = -1
實(shí)現(xiàn)文件下載,代碼如下:
- header('Content-Type: application/octet-stream');//設(shè)置內(nèi)容類(lèi)型
- header('Content-Disposition: attachment; filename="example.zip"'); //設(shè)置MIME用戶作為附件下載 如果將attachment換成inline意思為在線打開(kāi)
- header('Content-Transfer-Encoding: binary');//設(shè)置傳輸方式
- header('Content-Length: '.filesize('example.zip'));//設(shè)置內(nèi)容長(zhǎng)度
- // load the file to send:
- readfile('example.zip');//讀取需要下載的文件
php的函數(shù)header()可以向?yàn)g覽器發(fā)送Status標(biāo)頭,代碼如下:
header(”Status: 404 Not Found”)。
但是我發(fā)現(xiàn)實(shí)際上瀏覽器返回的響應(yīng)卻是如下代碼:
- // ok
- header(‘HTTP/1.1 200 OK’);
- //設(shè)置一個(gè)404頭:
- header(‘HTTP/1.1 404 Not Found’);
- //設(shè)置地址被永久的重定向
- 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
- //開(kāi)源軟件:phpfensi.com
- Content-Length: 0
- Keep-Alive: timeout=15, max=98
- Connection: Keep-Alive
- 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è)。
