まず、PHPでプログラミングを行う際、よく耳にすることが、問い合わせフォームをつくることを聞きます。
この記事では、PHPを使って
- 入力画面
- 確認画面
- 送信完了
という 3ステップ構成の問い合わせフォームを作成します。
フォーム全体の構成
今回使用するファイルは以下の3つです。
- index.php 入力画面
- confirm.php 確認画面
- send.php 送信処理
① 入力画面(index.php)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>お問い合わせ</title>
</head>
<body>
<h1>お問い合わせフォーム</h1>
<form action="confirm.php" method="post">
<p>
お名前<br>
<input type="text" name="name" required>
</p>
<p>
メールアドレス<br>
<input type="email" name="email" required>
</p>
<p>
お問い合わせ内容<br>
<textarea name="message" rows="5" required></textarea>
</p>
<button type="submit">確認画面へ</button>
</form>
</body>
</html>
ポイントは、required 属性で最低限の入力チェックや、method="post" を使用することです。
② 確認画面(confirm.php)
<?php
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
$message = htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8');
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>確認画面</title>
</head>
<body>
<h1>入力内容の確認</h1>
<p><strong>お名前</strong><br><?php echo $name; ?></p>
<p><strong>メールアドレス</strong><br><?php echo $email; ?></p>
<p><strong>お問い合わせ内容</strong><br>
<?php echo nl2br($message); ?></p>
<form action="send.php" method="post">
<input type="hidden" name="name" value="<?php echo $name; ?>">
<input type="hidden" name="email" value="<?php echo $email; ?>">
<input type="hidden" name="message" value="<?php echo $message; ?>">
<button type="submit">送信する</button>
</form>
<form action="index.php" method="get">
<button type="submit">修正する</button>
</form>
</body>
</html>
ポイントは下記の通り、
● htmlspecialchars() で XSS対策
● nl2br() で改行を表示
● hiddenフィールドで値を保持
● 「修正する」ボタンを用意すると親切
③ 送信処理(send.php)
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'your-email@example.com';
$subject = 'お問い合わせが届きました';
$body = <<<EOT
お名前:{$name}
メールアドレス:{$email}
【お問い合わせ内容】
{$message}
EOT;
$headers = "From: noreply@example.com";
mb_language("Japanese");
mb_internal_encoding("UTF-8");
if (mb_send_mail($to, $subject, $body, $headers)) {
echo '<p>送信が完了しました。お問い合わせありがとうございます。</p>';
} else {
echo '<p>送信に失敗しました。</p>';
}
よくある質問・注意点
Q. 確認画面はなぜ必要?
- 誤送信防止
- 入力ミスの軽減
- ユーザー体験(UX)の向上
Q. 本番運用で必要な対策は?
- CSRF対策(トークン)
- サーバー側バリデーション
- Fromアドレスの固定
- reCAPTCHA導入
まとめ
PHPを使えば、
確認画面付きの問い合わせフォームもシンプルに実装できます。
まずは基本構造を理解し、
実際のサイトに合わせてデザインやセキュリティを強化していきましょう。

コメント