PHP解説 HTMLのフォームとPHPの受取処理②
テキスト入力ボックス
いろんな入力フォームを作って受付処理をしてみるよ。

頑張ってください。 いちじくちゃん。

【サンプルフォーム1】
<form action="" method="GET">
<p>入力内容</p>
<input type="text" name="sample_text010"/>
<input type="submit" value="そ~しん"/>
</form>
<?php
if (isset($_GET["sample_text010"])) { echo htmlspecialchars($_GET["sample_text010"]);
}
?>
【実行結果1】
※そ~しんを押しても、データは残りませんので、ご自由に試しください。
まずは、一番シンプルな形の入力フォームと受付処理を作った。

フォームのname属性の値の。。ここでは「sample_text010」という「name属性に値が入っているかどうか」を目印にしてPHPは受け取り処理をしているんだ。

GET送信でURLを通して値が入れられているから、URLが「?sample_text010=入力値」に変わってますね。

また、受取時にはhtmlspecialchars関数でHTML タグを普通の文字列として出力させるようにして「クロスサイトスクリプティング対策」をしているんですね。

【サンプルフォーム2】
<form method="GET" action="#実行結果2">
<p>テキスト</p>
<input type="text" name="sample_text030">
<p>テキストエリア</p>
<textarea name="sample_text050" rows="7" cols="70">
</textarea><br>
<input type="submit" name="btn" value="そ~しん">
</form> <a id="実行結果2">【実行結果2】</a><br>
<?php
if (isset($_GET["sample_text030"]) || isset( $_GET["sample_text050"] )) { echo htmlspecialchars($_GET["sample_text030"]);
echo "<br>"; echo htmlspecialchars($_GET["sample_text050"]);
}
?>
【実行結果2】※そ~しんを押しても、データは残りませんので、ご自由に試しください。
これはテキストに加えて、テキストエリアの値も送って、両方表示させてるんだ。

name属性の値を変えれば、複数の値を送って、受け取ることができるんですね。

そう、ここではname属性の値を「sample_text030」と「sample_text050」とそれぞれ設定して、「sample_text030」と「sample_text050」にテキスト欄で入力した値を入れて送ってる。

それに今回は実行結果2の文字のところに以下のようにアンカーポイントを設定して、formの宛先を指定するactionのところで「#実行結果2」を指定しているんだ。

【アンカーポイントの設定例】
<a id="実行結果2">表示文字</a>
このようにアンカーポイントを宛先に設定しておけば、ページの一番上から見返さなくてもよくて便利ですね。

【サンプルフォーム3】
<form method="POST" action="#実行結果3">
<p>テキスト</p>
<input type="text" name="sample_text030" value="いちじく">
<p>テキストエリア</p>
<textarea name="sample_text050" rows="7" cols="70">
</textarea><br>
<INPUT type="hidden" name="送った" value="見て">
<input type="submit" name="btn" value="そ~しん">
</form> <a id="実行結果3">【実行結果3】</a><br>
<?php
if(isset($_POST['送った']) && $_POST['送った'] == '見て') { echo htmlspecialchars($_POST["sample_text030"]);
echo "<br>"; echo htmlspecialchars($_POST["sample_text050"]);
}
?>
【実行結果3】※そ~しんを押しても、データは残りませんので、ご自由に試しください。
次に作ったのは、、、POST送信にしてますね。POST送信にするにはGETのところをPOSTと単純に書き換えるだけなんですね。

また、受取時の条件を変えていますね。 inputのtype属性で"hidden"を指定して、ブラウザに何も表示させない形で、name属性の「送った」の中身に「見て」を入れて送っているんですね。

うん、受取時は「送った」を受け取って、中身が「見て」だったら、表示処理をするんだ。

この「見て」が一意の値であれば、他のPOST送信があっても誤作動しなくて安心。

あと「value="いちじく"」って、value属性を入れて入力値の初期表示を設定した💨

お名前