3
3

More than 3 years have passed since last update.

PHP入門 - お問い合わせフォームを作ろう (1)

Last updated at Posted at 2020-07-04

php.png

PHPを持っていない方は事前にインストールしておいてください。

フォーム画面の作成

任意のディレクトリにindex.phpを作成します。

index.php
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>お問合せフォーム</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <form action="" method="POST">
            <h4 class="py-4 text-center">お問い合わせ</h4>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputName">お名前(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <input type="text" name="name" id="inputName" class="form-control rounded-0" required autofocus>
                        <p class="error_msg text-danger">※お名前をご記入下さい</p>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputEmail">メールアドレス(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <input type="email" name="email" id="inputEmail" class="form-control rounded-0" required>
                        <p class="error_msg text-danger">※メールアドレスをご記入下さい</p>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputContent">お問い合わせ内容(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <textarea name="contact" id="inputContent" rows="10" class="form-control rounded-0" required></textarea>
                        <p class="error_msg text-danger">※お問い合わせ内容をご記入下さい</p>
                    </div>
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-8 col-offset-2">
                    <button type="submit" class="btn btn-primary w-100 rounded-0">確認画面へ</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

ブラウザで確認すると、下の画面のようになっているのがわかります。

img1.png

入力チェック

サーバ側で入力チェックをするために、novalidateを追加します。

index.php
<form action="" method="POST" novalidate> // 追記

次に<!DOCTYPE>の上にPHPのコードを書いていきます。

index.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

    if ($post['name'] === '') {
        $error['name'] = 'blank';
    }
}
?>

名前が未入力のとき、変数名$errorに'blank'という値が入るようにします。
そして、名前入力欄に下記のコードを追加します。

index.php
<input type="text" name="name" id="inputName" class="form-control rounded-0" required autofocus>
// ここから
<?php if ($error['name'] === 'blank'): ?>
    <p class="error_msg text-danger">※お名前をご記入下さい</p>
<?php endif; ?>
// ここまで

ブラウザを更新します。すると、

img2.png

名前入力欄の下に表示されていたエラーメッセージが消えました。
空欄のまま「確認画面へ」ボタンを押してみてください。「※お名前をご記入ください」というエラーメッセージが表示されるはずです。
これで名前の入力チェックは完了です。

入力していた文字をそのまま残す

今の状態で「確認画面へ」ボタンを押すと、エラー時に入力していた文字が消えてしまいます。そこで、value属性を追加します。

index.php
<input type="text" name="name" id="inputName" class="form-control rounded-0" value="<?php echo htmlspecialchars($post['name']); ?>" required autofocus>

これでエラーになっても直前に入力していた文字が消えずに残るようになりました。

この調子で、メールアドレスとお問い合わせ内容を編集していきます。

index.phpの内容は下記の通りになります。

index.php
<?php
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

    if ($post['name'] === '') {
        $error['name'] = 'blank';
    }
    if ($post['email'] === '') {
        $error['email'] = 'blank';
    }
    if ($post['contact'] === '') {
        $error['contact'] = 'blank';
    }
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>お問合せフォーム</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <form action="" method="POST" novalidate>
            <h4 class="py-4 text-center">お問い合わせ</h4>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputName">お名前(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <input type="text" name="name" id="inputName" class="form-control rounded-0" value="<?php echo htmlspecialchars($post['name']); ?>" required autofocus>
                        <?php if ($error['name'] === 'blank'): ?>
                            <p class="error_msg text-danger">※お名前をご記入下さい</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputEmail">メールアドレス(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <input type="email" name="email" id="inputEmail" class="form-control rounded-0" value="<?php echo htmlspecialchars($post['email']); ?>" required>
                        <?php if ($error['email'] === 'blank'): ?>
                            <p class="error_msg text-danger">※メールアドレスをご記入下さい</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputContent">お問い合わせ内容(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <textarea name="contact" id="inputContent" rows="10" class="form-control rounded-0" required><?php echo htmlspecialchars($post['contact']); ?></textarea>
                        <?php if ($error['contact'] === 'blank'): ?>
                            <p class="error_msg text-danger">※お問い合わせ内容をご記入下さい</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-8 col-offset-2">
                    <button type="submit" class="btn btn-primary w-100 rounded-0">確認画面へ</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

ブラウザを更新し、ご自身で動作確認をしてみてください。

img3.png

メールアドレスのバリデーション

メールアドレスが書式通り(XXXXXX@XXX.XXX)になっているかどうかをチェックします。メールアドレスの条件式に追記します。

index.php
if ($post['email'] === '') {
    $error['email'] = 'blank';
} else if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
    $error['email']= 'email';
}

メールアドレス入力欄にエラーメッセージを追加します。

index.php
<?php if ($error['email'] === 'email'): ?>
    <p class="error_msg text-danger">※メールアドレスを正しくご記入下さい</p>
<?php endif; ?>

ブラウザを更新し、動作確認をします。

img4.png

正しく動作していることがわかります。これでメールアドレスの書式チェックは完了です。

確認画面への移動

コードを追加します。

index.php
<?php
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

    if ($post['name'] === '') {
        $error['name'] = 'blank';
    }
    if ($post['email'] === '') {
        $error['email'] = 'blank';
    } else if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
        $error['email']= 'email';
    }
    if ($post['contact'] === '') {
        $error['contact'] = 'blank';
    }
    // ここから
    if (count($error) === 0) {
        header('Location: confirm.php');
        exit();
    }
    // ここまで
}
?>

これで「確認画面へ」ボタンを押すと、入力した内容に問題がなければconfirm.phpにページが移動します。

まだconfirm.phpを作成していないので、作成しましょう。index.phpの中身をほとんどそのままコピペした内容になっています。

confirm.php
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>送信内容確認</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <form action="./confirm.php" method="POST">
            <h4 class="py-4 text-center">確認画面</h4>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputName">お名前(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <p>テスト</p>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputEmail">メールアドレス(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <p>test@test.com</p>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-offset-2">
                        <label for="inputContent">お問い合わせ内容(必須)</label>
                    </div>
                    <div class="col-md-8 col-offset-2">
                        <p>テスト</p>
                    </div>
                </div>
            </div>
            <div class="row justify-content-center">
                <div class="col-md-8 col-offset-2">
                    <a href="index.php" class="btn btn-primary rounded-0">戻る</a>
                    <button type="submit" class="btn btn-primary rounded-0">送信する</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

これでindex.phpからconfirm.phpにページが移動できるようになりました。

img5.png

現時点では、index.phpで記入した内容はconfirm.phpに反映されていません。

次回はセッションを有効にし、ページをまたいでも値が保持できるようにしましょう。

PHP入門 - お問い合わせフォームを作ろう (2)

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3