http://www.codefactorycr.com/login-with-codeigniter-php.html
CodeIgniter
is an open source Web Application framework built in PHP designed to
make your life as a programmer easier, while allowing you good speed for
development, and also good performance when the site is up and running.
Being a Java developer for almost 10 years now, when I had to move to PHP I chose CodeIgniter for the following reasons:
- Easy to install and configure (being a newbie in PHP this was crucial)
- Clean and elegant MVC implementation
- Uses Active Record pattern for database access
- Overall small footprint and good performance
Usually when you are building a program, the login/logout
functionality is a must we always have to go through, so this quick
tutorial will focus on this functionality, taking advantage of the
benefits of using CodeIgniter instead of doing it from scratch in PHP.
Requirements
- CodeIgniter framework. By the time this tutorial was done, the latest version was 2.0.2
- Any Apache/PHP/MySQL stack. You can install the applications
independently, or install one of those packages that have all of them
bundled together.
Installing CodeIgniter
To install CodeIgniter, you only need to uncompress the Zip file you download from the site into your
htdocs directory and you’re good to go. We’ll configure the database access later.
Create the database
For this tutorial, you need a MySQL database with the following table:
2 | `id` tinyint(4) NOT NULL AUTO_INCREMENT, |
3 | `username` varchar(10) NOT NULL, |
4 | `password` varchar(100) NOT NULL, |
6 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; |
Remember also to add at least one user. We’ll add one user called
bob with password
supersecret.
1 | insert into users (username, password) values ('bob', MD5('supersecret')); |
Configure CodeIgniter
Database Access
Update the file
application/config/database.php in your CodeIgniter installation with your database info:
44 | $db['default']['hostname'] = 'localhost'; |
45 | $db['default']['username'] = 'yourdbusername'; |
46 | $db['default']['password'] = 'yourdbpassword'; |
47 | $db['default']['database'] = 'yourdbname'; |
Default Controller
We need to tell CodeIgniter to land into our login page instead of the default welcome page. Update the file
application/config/routes.php in your CodeIgniter installation with you controller’s name. We’ll call our landing controller
login.
41 | $route['default_controller'] = "login"; |
Default Libraries
In the file
application/config/autoload.php you can
configure the default libraries you want to load in all your
controllers. For our case, we’ll load the database and session
libraries, since we want to handle user sessions, and also the URL
helper for internal link generation
55 | $autoload['libraries'] = array('database','session'); |
67 | $autoload['helper'] = array('url'); |
Encryption Key
When you use the
session library, you need to set the
encryption_key in the file
application/config/config.php.
227 | $config['encryption_key'] = 'REALLY_LONG_NUMBER'; |
The Code
Here are the actual Views, Controllers and Model we are using for the login functionality.
User Model (application/models/user/php)
2 | Class User extends CI_Model |
4 | function login($username, $password) |
6 | $this -> db -> select('id, username, password'); |
7 | $this -> db -> from('users'); |
8 | $this -> db -> where('username = ' . "'" . $username . "'"); |
9 | $this -> db -> where('password = ' . "'" . MD5($password) . "'"); |
10 | $this -> db -> limit(1); |
12 | $query = $this -> db -> get(); |
14 | if($query -> num_rows() == 1) |
16 | return $query->result(); |
Login Controller (application/controllers/login.php)
1 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); |
3 | class Login extends CI_Controller { |
12 | $this->load->helper(array('form', 'url')); |
13 | $this->load->view('login_view'); |
Login View (application/views/login_view.php)
4 | <title>Simple Login with CodeIgniter</title> |
7 | <h1>Simple Login with CodeIgniter</h1> |
8 | <?php echo validation_errors(); ?> |
9 | <?php echo form_open('verifylogin'); ?> |
10 | <label for="username">Username:</label> |
11 | <input type="text" size="20" id="username" name="username"/> |
13 | <label for="password">Password:</label> |
14 | <input type="password" size="20" id="passowrd" name="password"/> |
16 | <input type="submit" value="Login"/> |
VerifyLogin Controller (application/controllers/verifylogin.php)
This controller does the actual validation of the fields and checks the credentials against the database.
1 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); |
3 | class VerifyLogin extends CI_Controller { |
8 | $this->load->model('user','',TRUE); |
14 | $this->load->library('form_validation'); |
16 | $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); |
17 | $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database'); |
19 | if($this->form_validation->run() == FALSE) |
22 | $this->load->view('login_view'); |
27 | redirect('home', 'refresh'); |
32 | function check_database($password) |
35 | $username = $this->input->post('username'); |
38 | $result = $this->user->login($username, $password); |
42 | $sess_array = array(); |
43 | foreach($result as $row) |
47 | 'username' => $row->username |
49 | $this->session->set_userdata('logged_in', $sess_array); |
55 | $this->form_validation->set_message('check_database', 'Invalid username or password'); |
Home Controller (application/controllers/home.php)
This is the private page (only authenticated users can access it).
1 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); |
3 | class Home extends CI_Controller { |
12 | if($this->session->userdata('logged_in')) |
14 | $session_data = $this->session->userdata('logged_in'); |
15 | $data['username'] = $session_data['username']; |
16 | $this->load->view('home_view', $data); |
21 | redirect('login', 'refresh'); |
27 | $this->session->unset_userdata('logged_in'); |
29 | redirect('home', 'refresh'); |
Home Page View (application/views/home_view.php)
4 | <title>Simple Login with CodeIgniter - Private Area</title> |
8 | <h2>Welcome <?php echo $username; ?>!</h2> |
9 | <a href="home/logout">Logout</a> |
The code is pretty easy to follow and understand. Also,
you can download the code from here,
so you can install it and test it in your location. You’ll only need a
full installation of CodeIgniter 2.0.2 and the table in your MySQL
database. If you need any help, feel free to leave us a comment or
shoot us an email.
Also, this code uses a pretty basic form validation from CodeIgniter. If you need a more complex validation process, check
CodeIgniter’s Form Validation docs at their site.
No comments:
Post a Comment