FuelPHP・ユーザー管理4:ログインするページ
FuelPHPでユーザー管理をやりたい4。ログインするページを用意する。
流れ
前回作ったコントローラに追加、ビューを新規作成
コントローラの作成
先に作ったコントローラに「action_login()」を追加
▼「fuel/app/classes/controller/sample1.php」
use \Auth;
class Controller_Sample1 extends Controller {
public function action_add_user() {
$view = View::forge(‘sample1/add_user’);
if ($_POST) {
//POSTデータを受け取る
$username = Input::post(‘username’);
$password = Input::post(‘password’);
$email = Input::post(‘email’);
// Authのインスタンス化
$auth = Auth::instance();
//ユーザー登録
$auth->create_user($username, $password, $email);
}
return $view;
}
public function action_login() {
$view = View::forge(‘sample1/login’);
$data = array();
if ($_POST) {
// Authのインスタンス化
$auth = Auth::instance();
// 資格情報の確認
if ($auth->login($_POST[‘username’], $_POST[‘password’])) {
// 認証OKならトップページ:
Response::redirect(‘index’);
}
else {
//認証が失敗したときの処理
$view->set(“username” , $_POST[‘username’]);
$view->set(“login_error”, ‘ユーザー名かパスワードが違います。再入力して下さい。’);
}
}
else {
$view->set(“username” , “”);
$view->set(“login_error”, “”);
}
return $view;
}
}
ビューの作成
ログイン画面
▼「fuel/app/views/sample1/login.php」
<html>
<head>
<meta charset=”utf-8″>
<title>ログイン</title>
</head>
<body>
<form name=”form1″ method=”post” action=””>
<?php echo $login_error?>
<table width=”100%” border=”1″>
<tr>
<th scope=”row”>ユーザー名</th>
<td><label for=”username”></label>
<input name=”username” type=”text” id=”username” value=”<?php echo $username; ?>” /></td>
</tr>
<tr>
<th scope=”row”>パスワード</th>
<td><label for=”password”></label>
<input type=”password” name=”password” id=”password” /></td>
</tr>
<tr>
<th colspan=”2″ scope=”row”><input type=”submit” name=”button” id=”button” value=”送信”></th>
</tr>
</table>
</form>
</body>
</html>
ルーティングの設定
「fuel/app/classes/controller/sample1.php」の「action_login()」の「Response::redirect(‘index’)」のときの処理が必要。
おそらく「そんなページ無いよ」って怒られると思う。
そのためルーティング・コントローラ・ビューファイルを適切に処理しておく(※「fuelPHPのルーティング設定」参照)
ログインチェック
「http://○○○/sample1/login」でアクセスして実際にログインできるかチェックする。
ログイン失敗したらエラー表示、成功したら「http://○○○/index」が表示される。