プログラム作成の大まかな流れ
CodeIgniterを最近始めた方にも会員登録とログイン機能の実装方法が分かるように、できるだけ分かりやすい簡単なコードで詳しく説明していきます。
コードの作成は以下の手順で行っていきます。少し長いのですが、軽く目を通しておくと全体の流れが掴めると思います。
データベースの設定 ユーザ登録用のテーブルの作成 CodeIgniterの初期セットアップ モデルの初期設定 コントローラの初期設定 会員登録ページに必要なmodel作成 ユーザ情報をDBにインサートするメソッドを作成 会員登録ページのcontroller作成 バリデーションの作成 バリーデーションを実行した時の場合分け 失敗→もう一度登録ページに飛ばす 成功→モデルの登録メソッドを使い、ユーザ情報をインサート インサート成功もしくは不成功のメッセージを表示 会員登録ページのview作成 ログインページに必要なmodel作成 POSTされたemailとpasswordの情報に一致する情報を取得 ログインページのcontroller作成 POSTされたemailと passwordのバリデーションチェック バリーデーションを実行した時の場合分け 失敗→もう一度ログインページに飛ばす 成功→モデルのログインメソッドを使い、一致する情報があるかチェック 情報がある→セッションを埋め込む ログアウトページに遷移 ログアウトページのcontroller作成 セッションを破棄するメソッドを作成 ログアウトページのview作成
データベースにテーブルを作成する
ユーザー登録用のデータベースを作成していきます。テーブル名は「 users 」とし、設定は以下のようにしていきます。
Id | int | 3 | primary |
Name | varchar | 255 | – |
varchar | 255 | – | |
Password | varchar | 255 | – |
CodeIgniterの初期セットアップ
.htaccss の作成
まず、applicationフォルダと同じ階層に.htaccssを追加しましょう。
コードは以下になります。
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule>
インデックスページの情報の変更
次にインデックスページの情報を変更します。
編集ファイル:application/config/ config.php
$config['index_page'] = '';
これはURLに付加されるindex.phpを外すために必要な作業です。
データベースとCodeIgniter紐付ける
データベースのオートロード設定を行います。
編集ファイル:application/config/autoload.php
この時ついでセッションライブラリのオートロード設定も済ませましょう。
/* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in system/libraries/ or your | application/libraries/ directory, with the addition of the | 'database' library, which is somewhat of a special case. | | Prototype: | | $autoload['libraries'] = array('database', 'email', 'session'); | | You can also supply an alternative library name to be assigned | in the controller: | | $autoload['libraries'] = array('user_agent' => 'ua'); */ $autoload['libraries'] = array('database',’session’);
次にデータベースの情報を入力します。
編集ファイル:application/config/ database.php
$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => ' users ', 'dbdriver' => 'mysqli',
ヘルパー機能の設定
編集ファイル:application/config/autload.php
| ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('form','url');
モデルとコントローラの初期設定
次にモデルとコントローラの初期設定をします。
具体的にはコードを通して使用頻度の高いヘルパーとライブラリを先に読み込んでおく作業です。
まずはモデルです。
User_model.phpを作成し、以下のパスに保存します。
application/models/User_model.php
コードは以下になります。
class User_model extends CI_Model { public function __construct() { $this->load->database(); }
簡単に説明しますね。
CI_Modelを継承して、User_modelを作成します。この時に注意ですが、クラスの頭文字は大文字にしなければなりません。
次にコンストラクタを使って、databaseライブラリをロードします。
コンストラクタとはインスタンス作成時に実行されるメソッドのことです。
次にコントローラです。以下のパスにUser.phpを作成し、保存しましょう。
application/controllers/User.php
class User extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('user_model'); $this->load->helper(array('form', 'url')); $this->load->library(array('session', 'form_validation')); }
会員登録ページの作成
会員登録ページに必要なmodel作成
会員登録に必要なメソッドをモデルに書いていきます。
会員情報をDBにインサートするメソッドです。コンストラクタの後に書きましょう。
作成ファイル:aplication/models/ User_model.php
public function set_user() { $data = array( 'firstname' => $this->input->post('firstname'), 'lastname' => $this->input->post('lastname'), 'email' => $this->input->post('email'), 'password' => md5($this->input->post('password')) ); return $this->db->insert('user', $data); }
POSTで受け取った各変数をuserテーブルにインサートしています。Passwordを受け取った時にmd5で暗号化しセキュリティーを向上させています。
ただし、実際の開発ではmd5のみではセキュリティーは不十分です。今回は簡単のためmd5のみを使用しています。
会員登録ページのcontroller作成
コントローラに会員登録ページのメソッドを作成していきましょう。コントローラのコンストラクタの下にコードを記述していきます。
作成ファイル:aplication/controllers/User.php
public function index() { $this->register(); } public function register() { $this->form_validation->set_rules('firstname', 'First Name', 'trim|required|alpha|min_length[3]|max_length[50]'); $this->form_validation->set_rules('lastname','Last Name','trim|required|alpha|min_length[3]|max_length[50]'); $this->form_validation->set_rules('email','Email','trim|required|valid_email|is_unique[user.email]'); $this->form_validation->set_rules('password','Password','trim|required|matches[cpassword]'); $this->form_validation->set_rules('cpassword','Confirm Password','trim|required'); $data['title'] = 'Register'; if($this->form_validation->run() === FALSE) { $this->load->view('user/register'); } else { if ($this->user_model->set_user()) { $this->session->set_flashdata('msg_success','Registration Successful!'); redirect('user/register'); } else { $this->session->set_flashdata('msg_error','Error! Please try again later.'); redirect('user/register'); } } }
区切って解説します。なお、説明していない部分もあるので、コピペする場合は上記のコードを使ってください。
public function index() { $this->register(); }
Indexメソッドではregisterに処理を渡しています。
public function register() { $this->form_validation->set_rules('firstname', 'First Name', 'trim|required|alpha|min_length[3]|max_length[50]'); $this->form_validation->set_rules('lastname','Last Name','trim|required|alpha|min_length[3]|max_length[50]'); $this->form_validation->set_rules('email','Email','trim|required|valid_email|is_unique[user.email]'); $this->form_validation->set_rules('password','Password','trim|required|matches[cpassword]'); $this->form_validation->set_rules('cpassword','Confirm Password','trim|required');
ビューページからpostで渡される情報のバリデーションを行います。
first name ,last nameではアルファベットのみ、文字の長さ制限を設けています。
emailではvalid_emailを使い、バリデーションチェックします。
valid_emailはフォームのデータが email アドレスとして正しくないとき FALSE を返します。
passwordでは確認用のパスワードcpasswordと一致するか確認しています。
if($this->form_validation->run() === FALSE) { $this->load->view('user/register'); }
バリデーションチェックをした時に正しくない入力があれば、もう一度会員登録ページに遷移させます。
else { if ($this->user_model->set_user()) { $this->session->set_flashdata('msg_success','Registration Successful!'); redirect('user/login'); } else { $this->session->set_flashdata('msg_error','Error! Please try again later.'); redirect('user/register'); } }
バリデーションチェックを行い、入力ミスが無ければ、モデルからset_userメソッドを呼び出し、会員情報をDBにインサートします。
このとき、インサートが成功したかどうかで条件分岐を行い、それぞれの実行結果メッセージをセッションに埋め込みます。Flashdataは一度呼び出されるとデータが自動的にクリアされるセッションです。実行結果が成功の場合、ログインページに遷移します。
会員登録ページのviewの作成
会員登録ページのビューを作成します。
<html> <head> <meta charset="Shift_JIS"> <title>CodeIgniter Registaraiton</title> </head> <body> <h1>Simple Registaraiton</h1> <a href="<?php echo site_url('user/register'); ?>">Register</a> | <a href="<?php echo site_url('user/login'); ?>">Login</a> <h4>User Registaraiton Form</h4> <?php $attributes = array("name" => "registration"); echo form_open("user/register", $attributes); ?> <table> <tr> <td><label for = "firstname">First Name</label></td> <td><input name="firstname" placeholder="First Name" type="text"><span><?php echo form_error('firstname'); ?></span></td> </tr> <tr> <td><label for = "lastname">Last Name</label></td> <td><input name="lastname" placeholder="Last Name" type="text"><span><?php echo form_error('lastname'); ?></span></td> </tr> <tr> <td><label for = "email"></label>Email ID</td> <td><input name="email" placeholder="Email ID" type="email"><span><?php echo form_error('email'); ?></span></td> </tr> <tr> <td><label for = "password"></label>Password</td> <td><input name="password" placeholder="Password" type="password"><span><?php echo form_error('password'); ?></span></td> </tr> <tr> <td><label for = "cpassword">Confirm Password</label></td> <td><input name="cpassword" placeholder="Confirm Password" type="password"><span><?php echo form_error('password'); ?></span></td> </tr> <tr> <td></td> <td><button name="submit" type="submit">Signup</button></td> </tr> </table> <?php echo form_close(); ?> </body> </html>
それでは区切って説明します。
<a href="<?php echo site_url('user/register'); ?>">Register</a> | <a href="<?php echo site_url('user/login'); ?>">Login</a>
登録ページとログインページへ遷移させるためのURLを設置しています。
site_urlの第1引数はモデルで、第2引数はメソッドになります。
<?php $attributes = array("name" => "registration"); echo form_open("user/register", $attributes); ?>
フォームタグを生成しています。この記事にform_openの詳しい使い方がありますので、時間がある方は読んでみてください。
<table> <tr> <td><label for = "firstname">First Name</label></td> <td><input name="firstname" placeholder="First Name" type="text"><span><?php echo form_error('firstname'); ?></span></td> </tr> <tr> <td><label for = "lastname">Last Name</label></td> <td><input name="lastname" placeholder="Last Name" type="text"><span><?php echo form_error('lastname'); ?></span></td> </tr> <tr> <td><label for = "email"></label>Email ID</td> <td><input name="email" placeholder="Email ID" type="email"><span><?php echo form_error('email'); ?></span></td> </tr> <tr> <td><label for = "password"></label>Password</td> <td><input name="password" placeholder="Password" type="password"><span><?php echo form_error('password'); ?></span></td> </tr> <tr> <td><label for = "cpassword">Confirm Password</label></td> <td><input name="cpassword" placeholder="Confirm Password" type="password"><span><?php echo form_error('password'); ?></span></td> </tr> <tr> <td></td> <td><button name="submit" type="submit">Signup</button></td> </tr> </table>
見た目をそろえるためにtableを使用しています。入力欄として、first name, last name, email, password , conform password を要求しています。
コードは長く見えますが、書いてある内容は大体一緒です。すみませんが、htmlタグについては説明を省略します。
form_errorはバリデーションチェックに引っかかった場合に、エラー内容を出力します。
この時の注意ですが、echoを忘れないでください。ビューページではechoしないとPHPで生成した要素が出力されないので、ページに反映されません。
これで会員登録ページの作成は終了です。ここで一度、実際に登録できるかテストしてみてください。DBに会員情報が記録されていれば成功です。ログインページ関連のコントローラを作成していないため、遷移が行われると404エラーがでるのは大丈夫です。
もし、DBに会員情報が記録されていなければ、下記のコードをコンストラクタの中(セッションライブラリなどのロードの下)に挿入してみてください。
if (ENVIRONMENT === 'development') { $this->output->enable_profiler(); }
これはCodeIgniterの各種デバック情報を表示してくれるコードです。
これを使用すれば、POSTがされていないのか、それともDBへのインサートがされていないのか、などが分かるためエラーコードの発見に役立ちます。
ログインページの作成
ログインページ に必要なmodel作成
ログインページを作成していきます。最初にログインに必要な機能をモデルに作成しましょう。コードは以下になります。
public function get_user_login($email, $password) { $query = $this->db->get_where('user', array('email' => $email, 'password' => md5($password))); return $query->row_array(); }
受け取った$emailと$passwordに一致するレコードを取得します。
get_whereの第1引数はテーブルです。第2引数は’調べるフィールド’=>’渡される変数’です。
Passwordはインサートする際にmd5で暗号化したので、検索をする時にもmd5をかけてからにしましょう。
ログインページのcontroller作成
コントローラを作成していきます。コードは以下になります。
public function login() { $email = $this->input->post('email'); $password =$this->input->post('password'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); $this->form_validation->set_rules('password', 'Password','trim|required|md5'); if($this->form_validation->run() === FALSE) { $this->load->view('user/login'); } else { if($user = $this->user_model->get_user_login($email, $password)) { $this->session->set_userdata('email',$email); $this->session->set_userdata('user_id',$user['id']); $this->session->set_userdata('is_logged_in', true); $this->load->view('user/logout'); } else { $this->session->set_flashdata('msg_error', 'Login credentials does match!'); redirect('user/login'); } } }
区切って解説していきます。
$email = $this->input->post('email'); $password =$this->input->post('password');
ビューページで入力された情報をPOSTで受け取って、それぞれの変数に代入しています。
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); $this->form_validation->set_rules('password', 'Password','trim|required|md5');
入力された情報のバリデーションチェックをしています。
if($this->form_validation->run() === FALSE) { $this->load->view('user/login'); }
バリデーションチェックを実行し、入力に誤りがある場合、再度ログインページに遷移させます。
else { if($user = $this->user_model->get_user_login($email, $password)) { $this->session->set_userdata('email',$email); $this->session->set_userdata('is_logged_in', true); $this->load->view('user/logout'); }
バリデーションチェックを通過し、入力に誤りがない場合、モデルのget_user_loginメソッドを使用します。DBに該当するemailとpasswordがあった場合、セッションを使用します。
$this->session->set_userdata('is_logged_in', true);
このコード1文でユーザがログインしているかどうかを判断します。ログイン後のページで’is_logged_in’がTRUEかFALSEか条件分岐を行うことでログインの状態を判別します。
$emailをセッションに埋め込むのはログイン後のページでどのユーザがログインしているかを表示するために使用します。
セッションを埋め込んだ後、$this->load->view(‘user/logout’); でログイン後のページに遷移します。
else { $this->session->set_flashdata('msg_error', 'Could not login!'); redirect('user/login'); }
DBに該当するemailとpasswordが無かった場合、エラーメッセージをセッションにフラッシュデータとして埋め込みましょう。
ログインページのviewの作成
ビューページを作成していきます。コードは以下になります。
<html> <head> <meta charset="Shift_JIS"> <meta name="keywords" content=""> <meta name="description" content=""> <title>CodeIgniter Login</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> </head> <body> <h1>Simple Login</h1> <a href="<?php echo site_url('user/register'); ?>">Register</a> | <a href="<?php echo site_url('user/login'); ?>">Login</a> <h4>User Login Form</h4> <?php $attributes = array("name" => "registration"); echo form_open("user/login", $attributes); ?> <table> <tr> <td><label for = "email"></label>Email ID</td> <td><input name="email" placeholder="Email ID" type="email"><span><?php echo form_error('email'); ?></span></td> </tr> <tr> <td><label for = "password"></label>Password</td> <td><input name="password" placeholder="Password" type="password"><span><?php echo form_error('password'); ?></span></td> </tr> <tr> <td></td> <td><button name="submit" type="submit">Login</button></td> </tr> </table> <?php echo form_close(); ?> <p style="color:green; font-style:bold"><?php echo $this->session->flashdata('msg_success'); ?></p> <p style="color:red; font-style:bold"><?php echo $this->session->flashdata('msg_error'); ?></p> </body> </html>
会員登録ページとほぼ同じなので、違う点だけ解説します。
<?php $attributes = array("name" => "registration"); echo form_open("user/login", $attributes); ?>
form_openでフォームタグを作成し、アクション先をコントローラのloginメソッドに指定します。
<p style="color:green; font-style:bold"><?php echo $this->session->flashdata('msg_success'); ?></p> <p style="color:red; font-style:bold"><?php echo $this->session->flashdata('msg_error'); ?></p>
set_flashdataを用いてセッションに埋め込んだメッセージを表示させます。
以上でログインページは完成です。
ログアウトページの作成
ログイン後のページを作成していきます。今回は簡単のために機能は
- どのユーザがログインしたかをemailを表示して確認できるようにする
- ログイン成功のメッセージを表示
- ログアウトボタンの設置
のみです。
ここまで作成してきた方にとっては簡単な作業になりますので、残りもサクサク作成していきましょう。
ログアウトページに関するモデルのメソッドはありませんので、コントローラの方から作成していきます。
ログアウトページのcontroller作成
コードは以下になります。
public function logout() { if ($this->session->userdata('is_logged_in')){ $this->session->unset_userdata('email'); $this->session->unset_userdata('is_logged_in'); $this->session->unset_userdata('user_id'); } redirect(base_url()); }
もし、’is_logged_in’がTRUEだった場合、’email’と’is_logged_in’のセッション情報を破棄します。その後、設定したbase_urlに遷移します。
以上で、コントローラの全メソッドの作成終了です。
次にログアウトページを作成しましょう。
ログアウトページのviewの作成
ビューページを作成します。コードは以下になります。
<html> <head> <meta charset="Shift_JIS"> <meta name="keywords" content=""> <meta name="description" content=""> <title>CodeIgniter Logout</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> </head> <body> <h1>Simple Logout</h1> <p> <?php if($this->session->userdata('is_logged_in') === true){ ?> <b>loggined as:</b> <?php echo $this->session->userdata('email'); ?> <?php }else{ redirect(base_url()); } ?> </p> <p>You have successfully logged in!</p> <input type="button" onclick="location.href='<?php echo site_url('user/logout'); ?>'" value="Logout"> </body> </html>
区切って説明します。
<?php if($this->session->userdata('is_logged_in') === true){ ?> <b>loggined as:</b> <?php echo $this->session->userdata('email'); ?> <?php }else{ redirect(base_url()); } ?>
‘is_logged_in’のセッションデータがあるか無いかでログイン状態を判断します。あればログインしているユーザのemailを表示します。無ければbase_urlに遷移します。
<input type="button" onclick="location.href='<?php echo site_url('user/logout'); ?>'" value="Logout">
ログアウトボタンになります。クリックした際にコントローラのlogoutメソッドにアクセスし、セッションを破棄した後、base_urlに遷移します。
これで完了です!最後まで読んでくださってありがとうございました!
コメント