header函數使用

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )php

----- 用於向客戶端發送原生的 HTTP 報頭,html

注意 瀏覽器

header() 必須在任何實際輸出以前調用,無論是普通的 HTML 標籤,仍是文件或 PHP 輸出的空行,空格。這是個常見的錯誤,例如在經過include,require,或者其訪問其餘文件裏面的函數的時候,若是在header()被調用以前,其中有空格或者空行。緩存

客戶機的請求方式格式:是統一資源標識符、協議版本號,後邊是MIME信息包括請求修飾符、客戶機信息和可能的內容服務器

服務器響應格式:一個狀態行包括信息的協議版本號、一個成功或錯誤的代碼,後邊是MIME信息包括服務器信息、實體信息和可能的內容。app

經常使用實例: 1.實現重定向(狀態碼302) Location函數

<?php
header(」Location: http://www.phpddt.com」);
exit; 
?>

注意:@1 Location 和:之間沒有空格 @2 在每一個重定向以後都必須加上「exit」,避免發生錯誤後,繼續執行。動畫

永久重定向(狀態碼301)ui

<?
Header( "HTTP/1.1 301 Moved Permanently" ) ;
Header( "Location: www.phpddt.com" );
?>

2.使用header在某個時間後執行跳轉url

header('Refresh: 10; url=http://www.example.org/')

10秒後跳轉到 http://www.example.org/頁面

固然,也能夠使用html語法實現
//<meta http-equiv="refresh" content="10;http://www.example.org/ />

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

php強制下載application/force-download,將發送HTTP 標頭您的瀏覽器並告訴它下載,而不是在瀏覽器中運行的文件。 最主要原理是根據:"Content-Type: application/force-download;"和"Content-Disposition: attachment;"來達到目的。 header("Content-Type: application/force-download;"); //告訴瀏覽器強制下載

4.設置文件內容類型 Content-Type

<?php
header(’Content-Type: text/html; charset=utf-8′);
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-shockw**e-flash'); //Flash動畫 
?>

5.狀態碼 status

頁面不存在(404頁面)

<?php 
header('HTTP/1.1 404 Not Found'); 
header("status: 404 Not Found"); 
?>

6.使用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, no-store, max-age=0, must-revalidate");
  header("Pragma: no-cache");
相關文章
相關標籤/搜索