PHP中header函數的用法及其注意事項詳解_php執行個體

來源:互聯網
上載者:User
void header ( string $string [, bool $replace = true [, int $http_response_code ]] ) : Send a raw HTTP header

下面有一些使用header的幾種用法:

1、使用header函數進行跳轉頁面;

  header('Location:'.$url);

  其中$url就是將要跳轉的url了。

  這種用法的注意事項有以下幾點:

•Location和":"之間不能有空格,否則會出現錯誤(注釋:我剛測試了,在我本地環境下,沒有跳轉頁面,但是也沒有報錯,不清楚什麼原因);

•在用header前不能有任何的輸出(注釋:這點大家都知道的,如果header之前有任何的輸出,包括空白,就會出現header already sent by xxx的錯誤);

•header 後面的東西還會執行的;

2、使用header聲明content-type

  header('content-type:text/html;charset=utf-8');
  這個沒有什麼好說的;

3、使用header返回response 狀態代碼

  header(sprintf('%s %d %s', $http_version, $status_code, $description));

  樣式就是這樣的;

  例如:header('HTTP/1.1 404 Not Found');

4、使用header在某個時間後執行跳轉

 header("Refresh: {$delay}; url={$url}");

 其中$delay就是延遲跳轉的時間,$url為需要跳轉的url

 例如:header('Refresh: 10; url=http://www.example.org/'); 意思為10s後跳轉到http://www.eexample.org這個網站

5、使用header控制瀏覽器緩衝

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-cache, must-revalidate");  header("Pragma: no-cache");

6、執行http驗證

  header('HTTP/1.1 401 Unauthorized');
  header('WWW-Authenticate: Basic realm="Top Secret"');

7、使用header進行下載操作

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'));//設定內容長度  // load the file to send:  readfile('example.zip');//讀取需要下載的檔案

下面再給大家介紹PHP header 的幾種用法

跳轉頁面

header('Location:'.$url); //Location和":"之間無空格。

聲明content-type

header('content-type:text/html;charset=utf-8');

返回response狀態代碼

header('HTTP/1.1 404 Not Found');

在某個時間後執行跳轉

header('Refresh: 10; url=http://www.baidu.com/'); //10s後跳轉。

控制瀏覽器緩衝

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-cache, must-revalidate");
header("Pragma: no-cache");

執行http驗證

header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');

執行下載操作

header('Content-Type: application/octet-stream'); //設定內容類型
header('Content-Disposition: attachment; filename="example.zip"'); //設定MIME使用者作為附件
header('Content-Transfer-Encoding: binary'); //設定傳輸方式
header('Content-Length: '.filesize('example.zip')); //設定內容長度

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.