PHP header()関数
完全な PHP HTTP リファレンスマニュアル
定義と使用法
header() 関数はクライアントに生の HTTP ヘッダーを送信します。
重要なのは、実際の出力が送信される前に header() 関数を呼び出す必要があることです(PHP 4 以降では、出力バッファリングを使用してこの問題を解決できます):
<html>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>
構文
header(string,replace,http_response_code)
| 引数 | 説明 |
|---|---|
| string | 必須。送信するヘッダー文字列を指定します。 |
| replace | 任意。このヘッダーが以前のヘッダーを置き換えるか、2 番目のヘッダーを追加するかを指定します。デフォルトは TRUE(置き換え)です。FALSE(同じタイプの複数のヘッダーを許可します)。 |
| http_response_code | 任意。HTTP レスポンスコードを指定した値に強制します。(PHP 4.3 以降で使用可能) |
ヒントと注釈
注釈:PHP 4.4 以降、この関数は一度に複数のヘッダーを送信することを防ぎます。これはヘッダーインジェクション攻撃に対する保護対策です。
例 1
ページキャッシュを無効にする:
<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
<html>
<body>
...
...
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
<html>
<body>
...
...
注釈:ユーザーはブラウザのデフォルトのキャッシュ設定を変更するいくつかのオプションを設定する可能性があります。上記のヘッダーを送信することで、これらの設定をすべて上書きし、ブラウザにキャッシュさせないように強制できます!
例 2
生成された PDF ファイルを保存するようユーザーに促します(Content-Disposition ヘッダーは推奨ファイル名を提供し、ブラウザに保存ダイアログを表示させます):
<?php
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");
// The PDF source is in original.pdf
readfile("original.pdf");
?>
<html>
<body>
...
...
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");
// The PDF source is in original.pdf
readfile("original.pdf");
?>
<html>
<body>
...
...
注釈:マイクロソフトの IE 5.5 には上記のメカニズムを妨げるバグがあります。Service Pack 2 以降にアップグレードすることで、このバグを解決できます。
完全な PHP HTTP リファレンスマニュアル その他の拡張