PHP 8.3.4 Released!

フォームの処理

PHP の最も強力な機能の一つは、HTML フォームを処理する手段です。 理解するべき重要な基本概念は、あるフォームの中の全てのフォーム要素が、 自動的に PHP スクリプトで利用可能になるということです。 詳細は、マニュアルのセクション 外部から来る変数 および PHP でフォームを使用する例を参照ください。以下に HTML フォームの例を示します。

例1 簡単な HTML フォーム

<form action="action.php" method="post">
    <label for="name">名前:</label>
    <input name="name" id="name" type="text">

    <label for="age">年齢:</label>
    <input name="age" id="age" type="number">

    <button type="submit">Submit</button>
</form>

このフォームに関して特別なところはありません。これは通常の HTML フォームで特殊なタグは全く使用していません。 ユーザーがこのフォームを記入し、投稿ボタンを押した時、 action.php ページがコールされます。 このファイルには、以下のようなコードを記述します。

例2 フォームからのデータを出力する

こんにちは、<?php echo htmlspecialchars($_POST['name']); ?>さん。
あなたは、<?php echo (int)$_POST['age']; ?> 歳です。

このスクリプトの出力例は次のようになります。

こんにちは、Joe さん。あなたは、22 歳です。

htmlspecialchars() および (int) の部分以外は、何を行っているかは明らかでしょう。 htmlspecialchars() は、html での特殊な文字を適切にエンコードし、 HTML タグや JavaScript をページ内に仕込めないようにします。 また、age フィールドには数値が入ることがわかっているので、これを int 型に 変換 します。これにより、おかしな文字が入力されることを防ぎます。 これらの処理を PHP に自動的に行わせるためには、 filter 拡張モジュールを使用します。 変数 $_POST['name']$_POST['age'] は PHP により自動的に設定されます。 前の部分では、スーパーグローバル$_SERVER を使用しましたが、 ここでは、全ての POST データを保持するスーパーグローバル $_POST を導入しています。 フォームのメソッドが POST であることに注意してください。 GET メソッドを使用している場合、 フォームの情報は代わりにスーパーグローバル $_GET に代入されます。リクエストデータの発信源に留意しない場合には、 スーパーグローバル変数 $_REQUEST を使用することもできます。この変数は、GET, POST, COOKIE, FILE データの混ざったものが含まれます。

XForms の入力を PHP で扱うことも可能ですが、たいていの場合は HTML フォームのほうが快適に使用できるでしょう。 XForms は初心者向けのものではありませんが、気になる人もいるかもしれません。 機能概要の節にある XForm から受信したデータの処理方法 を参照ください。

add a note

User Contributed Notes 2 notes

up
105
sethg at ropine dot com
20 years ago
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.

You should use the GET method when your form is, well, getting something off the server and not actually changing anything. For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.
up
8
Johann Gomes (johanngomes at gmail dot com)
13 years ago
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
To Top