WEB制作の備忘録|朧なる足痕

メールフォーム実習6:SESSION:入力ページ

check.phpからindex.phpに戻るときに入力した値を引き継ぐ

  1. 上部にphpを記述
  2. inputタグにvalueを追加
  3. textareaタグにはタグ内に追加
  4. 文字制限のお知らせをlabel終了タグの後ろに入れる

【index.php

<?php
function h($str){
  return htmlspecialchars($str,ENT_QUOTES,'utf-8');
}
session_start();
$name = '';
$email = '';
$message = '';
if(isset($_SESSION['name'])){
  $name = $_SESSION['name'];
}
if(isset($_SESSION['email'])){
  $email = $_SESSION['email'];
}
if(isset($_SESSION['message'])){
  $message = $_SESSION['message'];
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>お問い合わせフォーム</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>お問い合わせフォーム</h1>
<form action="check.php" method="post">
<table>
<tr>
<th><label for="name">お名前:</label>(20文字以内)</th><td><input type="text" name="name" id="name" value="<?php echo h($name); ?>"></td>
</tr>
<tr>
<th><label for="email">Eメール:</label>(25文字以内)</th><td><input type="text" name="email" id="email" value="<?php echo h($email); ?>"></td>
</tr>
<tr>
<th><label for="message">お問い合わせ:</label>(150文字以内)</th><td><textarea name="message" id="message"><?php echo h($message); ?></textarea></td>
</tr>
</table>
<input type="submit" value="確認">
</form>
</body>
</html>

ポイント

上部にphpを記述
  • postデータはindex.phpに戻せないのでsessionデータを代入します
  • 初めてブラウザを開くときに初期値がないとエラーになるためif文を使用します
    • 開発途中で検証する場合は以下を使用
    • @=エラー制御演算子、応急処置で使用
  $name = @$_SESSION['name'];
    • 後で下部のif文に修正
if(isset($_SESSION['name'])){
  $name = $_SESSION['name'];
}
出力
  • inputタグにvalueを追加
<input type="text" name="name" id="name" value="<?php echo h($name); ?>"></td>
  • textareaタグにはvalueがないのでタグ内に追加
<td><textarea name="message" id="message"><?php echo h($message); ?></textarea></td>