手順
新規登録画面の作成
今回は、ユーザ名
、メールアドレス
、パスワード
、パスワード確認
の4つのフォームを用意する
signup_form.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ユーザ登録画面</title>
</head>
<body>
<h2>ユーザ登録フォーム</h2>
<form action="register.php" method="POST">
<p>
<label for="username">ユーザ名:</label>
<input type="text" name="username">
</p>
<p>
<label for="email">メールアドレス:</label>
<input type="email" name="email">
</p>
<p>
<label for="password">パスワード:</label>
<input type="password" name="password">
</p>
<p>
<label for="password_conf">パスワード確認:</label>
<input type="password" name="password_conf">
</p>
<p>
<input type="submit" value="新規登録">
</p>
</form>
</body>
</html>
新規登録完了画面の作成
register.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ユーザ登録完了画面</title>
</head>
<body>
<p>ユーザー登録が完了しました。</p>
<a href="signup_form.php">戻る</a>
</body>
</html>
バリデーションの作成
入力フォームにて入力し、送信した後はregister.phpへ情報が飛んで、リンクに繋がる。
その時にregister.phpの方で、登録が完了したか、入力エラーがあるかどうかを表示させる仕組みを作成する。
なお、新規登録を完了させることができた場合の処理はのちに行う。
①入力エラーが存在するフォームそれぞれに対して、エラーの文字を配列で集めていく。
②一つでもエラーの配列の要素がある場合は、あるもの全てをforeachで表示させていく。
register.php
<?php
// エラーメッセージ
$err = [];
// バリデーション
if(!$username = filter_input(INPUT_POST, 'username')){
$err[] = 'ユーザ名を記入してください';
}
if(!$email = filter_input(INPUT_POST, 'email')){
$err[] = 'メールアドレスを記入してください';
}
$password = filter_input(INPUT_POST, 'password');
// 正規表現
if(!preg_match("/\A[a-z\d]{8,100}+\z/i", $password)){
$err[] = 'パスワードは英数字8文字以上100文字以下にしてください。';
}
$password_conf = filter_input(INPUT_POST, 'password_conf');
if($password !== $password_conf){
$err[] = '確認用パスワードと異なっています';
}
if(count($err) === 0){
//ユーザを登録する処理
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ユーザ登録完了画面</title>
</head>
<body>
<?php if (count($err) > 0) : ?>
<!-- エラーがある場合にforeachで該当エラーを表示させる -->
<?php foreach($err as $e) : ?>
<p><?php echo $e ?></p>
<?php endforeach; ?>
<!-- $err配列に何もない=エラーがない から完了画面を表示させる -->
<?php else: ?>
<p>ユーザー登録が完了しました。</p>
<?php endif ; ?>
<a href="signup_form.php">戻る</a>
</body>
</html>