PHP header 使用方法和介紹

2021-06-05 15:22:37 字數 1916 閱讀 4449

header() 函式向客戶端傳送原始的 http 報頭。

認識到一點很重要,即必須在任何實際的輸出被傳送之前呼叫 header() 函式(在 php 4 以及更高的版本中,您可以使用輸出快取來解決此問題):

<?php

// 結果出錯

// 在呼叫 header() 之前已存在輸出

header('location: ');

?>

header(string,replace,http_response_code)
引數

描述string

必需。規定要傳送的報頭字串。

replace

可選。指示該報頭是否替換之前的報頭,或新增第二個報頭。

預設是 true(替換)。false(允許相同型別的多個報頭)。

可選。把 http 響應**強制為指定的值。(php 4 以及更高版本可用)

注釋:從 php 4.4 之後,該函式防止一次傳送多個報頭。這是對頭部注入攻擊的保護措施。

例子1

<?php

// date in the past

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");

header("pragma: no-cache");

?>

......

注釋:使用者可能會設定一些選項來更改瀏覽器的預設快取設定。通過傳送上面的報頭,您可以覆蓋任何這些設定,強制瀏覽器不進行快取!

<?php

// 檔案將被稱為 downloaded.pdf

header("content-disposition:attachment;filename='downloaded.pdf'");

// pdf 源在 original.pdf 中

readfile("original.pdf");

?>

......

注釋:微軟 ie 5.5 存在乙個阻止以上機制的 bug。通過公升級為 service pack 2 或更高的版本,可以解決該 bug。

例子3

重定向

// php header函式永久重定向

header(「location: 預設是301 跳轉

// 臨時重定向

例子4

向瀏覽器傳送404 狀態碼

或者header(「http/1.1 404″);

例子5

header(「content-type: text/plain』); // 可以替換成你需要的mime型別

header(『content-disposition: attachment; filename=」test.txt」『);

readfile(『test.txt』);

其他的頭資訊可以參考http/1.1 specification

如果在php header函式之前已經有了輸出,那麼請使用ob_start()函式。

python之random模組使用方法介紹

import random print random.random 0,1 float 大於0且小於1之間的小數 print random.randint 1,3 1,3 大於等於1且小於等於3之間的整數 print random.randrange 1,3 1,3 大於等於1且小於3之間的整數 p...

AspUpload元件的安裝及使用方法介紹

aspupload對asp程式設計人員來說要實現asp 檔案上傳功能它是首選。本文就為大家介紹一下aspupload元件的安裝及使用方法,其中還附帶了aspupload安裝的常見問題解答及乙個使用aspupload實現檔案上傳的例項。元件簡介 asp上傳元件,能夠實現以下功能 a.限制上載檔案的大小...

OC NSString基本使用和常用方法介紹

基本字元創 nsstring string1 hello world 基本字元創建立 nsstring action1 nsstring alloc init 建立乙個空字元創 nsstring string2 nsstring string 通過物件建立字串 不過一般不這麼建立 不推薦 nsstr...