php中header用法

來源:互聯網
上載者:User

header()函數的作用是:發送一個原始 HTTP 標題[Http Header]到用戶端。
標題 (header) 是伺服器以 HTTP 協義傳 HTML 資料到瀏覽器前所送出的字串,在標題
與 HTML 檔案之間尚需空一行分隔。有關 HTTP 的詳細說明,可以參 RFC 2068 官方檔案
(http://www.w3.org/Protocols/rfc2068/rfc2068)。
在 PHP 中送回 HTML 資料前,需先 傳完所有的標題。

使用範例

範例一: 本例使瀏覽器重新導向到 PHP 的官方網站。

<?PHP
Header("Location: http://www.php.net";);
exit;   //在每個重新導向之後都必須加上“exit",避免發生錯誤後,繼續執行。
?>
<?php
/**
@title:PHP定時跳轉
@功能:等待指定的時間,然後再跳轉到指定頁面(代替html meta方式)
*/
header("refresh:3;url=http://axgle.za.net");
print('正在載入,請稍等...<br>三秒後自動跳轉~~~');
/*
補充說明:
若等待時間為0,則與header("location:")等效。
*/
header重新導向 就等價於替使用者在地址欄輸入url
?>  

範例二:禁止頁面在IE中緩衝

要使用者每次都能得到最新的資料,而不是 Proxy 或 cache 中的資料,可以使用下列的標題

<?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

Expires是個好東東,如果伺服器上的網頁經常變化,就把它設定為-1,表示立即到期。如果一個網頁每天淩晨1點更新,可以把Expires設定為第二天的淩晨1點。
當HTTP1.1伺服器指定CacheControl = no-cache時,瀏覽器就不會緩衝該網頁。

舊式 HTTP 1.0 伺服器不能使用 Cache-Control 標題。所以為了向後相容 HTTP 1.0 伺服器,IE使用Pragma:no-cache 標題對 HTTP 提供特殊支援。
如果用戶端通過安全連線 (https://) 與伺服器通訊,且伺服器在響應中返回 Pragma:no-cache 標題,則 Internet Explorer 不會緩衝此響應。
注意:Pragma:no-cache 僅當在安全連線中使用時才防止緩衝,如果在非安全頁中使用,處理方式與 Expires:-1 相同,該頁將被緩衝,但被標記為立即到期。

http-equiv meta標記:

在html頁面中可以用http-equiv meta來標記指定的http訊息頭部。老版本的IE可能不支援html meta標記,所以最好使用http訊息頭部來禁用緩衝。

範例三: 讓使用者的瀏覽器出現找不到檔案的資訊。

網上很多資料這樣寫:php的函數header()可以向瀏覽器發送Status標題,
如 header(”Status: 404 Not Found”)。

但是我發現實際上瀏覽器返回的響應卻是:

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

查了一些資料,正確的寫法是:
header(”http/1.1 404 Not Found”);

第一部分為HTTP協議的版本(HTTP-Version);第二部分為狀態碼(Status);第三部分為原因短語(Reason-Phrase)。

範例四:讓使用者下載檔案( 隱藏檔案的位置 )

html標籤 就可以實現普通檔案下載。如果為了保密檔案,就不能把檔案連結告訴別人,可以用header函數實現檔案下載。
<?php
header("Content-type: application/x-gzip");
header("Content-Disposition: attachment; filename=檔案名稱/");
header("Content-Description: PHP3 Generated Data");
?>

範例四:header函數前輸入內容

一般來說在header函數前不能輸出html內容,類似的還有setcookie() 和 session 函數,這些函數需要在輸出資料流中增加訊息頭部資訊。如果在header()執行之前有echo等語句,當後面遇到header()時,就會報出 “Warning: Cannot modify header information - headers already sent by ….”錯誤。就是說在這些函數的前面不能有任何文字、空行、斷行符號等,而且最好在header()函數後加上exit()函數。例如下面的錯誤寫法,在兩個php程式碼片段之間有一個空行:

//some code here
?>
//這裡應該是一個空行
header(”http/1.1 403 Forbidden”);
exit();
?>

原因是:PHP指令碼開始執行 時,它可以同時發送http訊息頭部(標題)資訊和主體資訊. http訊息頭部(來自 header() 或 SetCookie() 函數)並不會立即發送,相反,它被儲存到一個列表中. 這樣就可以允許你修改標題資訊,包括預設的標題(例如 Content-Type 標題).但是,一旦指令碼發送了任何非標題的輸出(例如,使用 HTML 或 print() 調用),那麼PHP就必須先發送完所有的Header,然後終止 HTTP header.而後繼續發送主體資料.從這時開始,任何添加或修改Header資訊的試圖都是不允許的,並會發送上述的錯誤訊息之一。

解決辦法:

修改php.ini開啟緩衝(output_buffering),或者在程式中使用緩衝函數ob_start(),ob_end_flush()等。原理是:output_buffering被啟用時,在指令碼發送輸出時,PHP並不發送HTTP header。相反,它將此輸出通過管道(pipe)輸入到動態增加的緩衝中(只能在PHP 4.0中使用,它具有中央化的輸出機制)。你仍然可以修改/添加header,或者設定cookie,因為header實際上並沒有發送。當全部指令碼終止時,PHP將自動發送HTTP header到瀏覽器,然後再發送輸出緩衝中的內容。

=================================================================
PHP 手冊執行個體應用

1:您可以使用heder命令,強制使瀏覽器使用新鮮的內容(無緩衝) 。
也可以給網址增加了一個唯一的編號,使其每次都讀取新的內容,避免緩衝。
example:
<?
print "<img src='yourfile.jpg'>";   //通常讀取的是快取檔案
?>

<?
print "<img src='yourfile.jpg?".time()."'>";   //增加了唯一的編號,使瀏覽器重新請求

w//print "<img src='yourfile.jpg?".rand(100,999)."'>";
?>

2: 下面是個很好的函數,將圖片傳送給瀏覽器顯示。
<?php
function PE_img_by_path($PE_imgpath = "")
{
    if (file_exists($PE_imgpath)) {
        $PE_imgarray = pathinfo($PE_imgpath);

        $iconcontent = file_get_contents($PE_imgpath);
        header("Content-type: image/" . $PE_imgarray["extension"]);
        header('Content-length: ' . strlen($iconcontent));
        echo $iconcontent;
        die(0);
    }
    return false;
}
?>
更多的執行個體:

<?php

// ok
header('HTTP/1.1 200 OK');

//設定一個404頭:
header('HTTP/1.1 404 Not Found');

//設定地址被永久的重新導向
header('HTTP/1.1 301 Moved Permanently');

//轉到一個新地址
header('Location: http://www.example.org/');

//檔案延遲轉向:
header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';

//當然,也可以使用html文法實現
// <meta http-equiv="refresh" content="10;http://www.example.org/ />

// override X-Powered-By: PHP:
header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');

//文檔語言
header('Content-language: en');

//告訴瀏覽器最後一次修改時間
$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');

//告訴瀏覽器文檔內容沒有發生改變
header('HTTP/1.1 304 Not Modified');

//設定內容長度
header('Content-Length: 1234');

//設定為一個下載類型
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');

// 對當前文檔禁用緩衝
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');

//設定內容類型:
header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); //純文字格式
header('Content-Type: image/jpeg'); //JPG圖片
header('Content-Type: application/zip'); // ZIP檔案
header('Content-Type: application/pdf'); // PDF檔案
header('Content-Type: audio/mpeg'); // 音頻檔案
header('Content-Type: application/x-shockwave-flash'); //Flash動畫

//顯示登陸對話方塊
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.