If you have finished our previous tutorial, we can start this tutorial now. The CI classes we have to learn in this tutorial are session and form validation. I believe that you would be familiar with PHP session.
Requirement
Download the latest CI version from the following link.CodeIgniter
Step 1:Configuration
Open application/config/database.php, and change the following database configuration to fit your mysql configuration.$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
Then open application/config/config.php
$config['base_url'] = 'http://localhost/ci_user';
$config['encryption_key'] = '1234';
Open application/config/autoload.php
$autoload['libraries'] = array('session','database');
and
$autoload['helper'] = array('url','form');
Open application/config/routes.php, change default controller to user controller as we’ll create later on this tutorial.
$route['default_controller'] = 'user';
Step 2:Creating User table
We need to create a table in our database. Import following SQL statement via phpMyAdmin or any other MySQL tool.CREATE TABLE `user` ( `id` INT( 50 ) NOT NULL AUTO_INCREMENT , `username` VARCHAR( 50 ) NOT NULL , `email` VARCHAR( 100 ) NOT NULL , `password` VARCHAR( 255 ) NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = InnoDB
Step 3:Creating our Controller
Create a blank document in the controller file (application -> controller) and name it user.php, in the document add all the following code.<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function index()
{
if(($this->session->userdata('user_name')!=""))
{
$this->welcome();
}
else{
$data['title']= 'Home';
$this->load->view('header_view',$data);
$this->load->view("registration_view.php", $data);
$this->load->view('footer_view',$data);
}
}
public function welcome()
{
$data['title']= 'Welcome';
$this->load->view('header_view',$data);
$this->load->view('welcome_view.php', $data);
$this->load->view('footer_view',$data);
}
public function login()
{
$email=$this->input->post('email');
$password=md5($this->input->post('pass'));
$result=$this->user_model->login($email,$password);
if($result) $this->welcome();
else $this->index();
}
public function thank()
{
$data['title']= 'Thank';
$this->load->view('header_view',$data);
$this->load->view('thank_view.php', $data);
$this->load->view('footer_view',$data);
}
public function registration()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('email_address', 'Your Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$this->user_model->add_user();
$this->thank();
}
}
public function logout()
{
$newdata = array(
'user_id' =>'',
'user_name' =>'',
'user_email' => '',
'logged_in' => FALSE,
);
$this->session->unset_userdata($newdata );
$this->session->sess_destroy();
$this->index();
}
}
?>if(($this->session->userdata('user_name')!=""))
the above code is equal to the following code in php.
if($_SESSION['user_name']!="")
It means that if the user_name is not equal to the null, this user have already logged in. So we will go to welcome() function. Else we will show registration from view.
You will understand next login() and thank() functions I think.
In the registration() function, firstly we load the form_validation library. And then we set the rules for our form field. The trim rule is equal to the php trim() function and you will understand the others I think. And then we run the form validation. If the result is false, we will go to index() function. Else we will add user data and will go to thank() function.
In the logout() function, we will unset and destroy the session data and will go to the index() function.
Step 4:Creating Model
Create a blank document in the model file (application -> model) and name it user_model.php, in the document add all the following code.<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
function login($email,$password)
{
$this->db->where("email",$email);
$this->db->where("password",$password);
$query=$this->db->get("user");
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->username,
'user_email' => $rows->email,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
public function add_user()
{
$data=array(
'username'=>$this->input->post('user_name'),
'email'=>$this->input->post('email_address'),
'password'=>md5($this->input->post('password'))
);
$this->db->insert('user',$data);
}
}
?>$this->db->where("email",$email);
$this->db->where("password",$password);
the above two line will produce the following query in MySQL:
WHERE email='$email' AND password='$password'
$this->session->set_userdata($newdata);
This above code will set our user data to the session variable.
Step 5:Designing our view files
Create a blank document in the views file (application -> views) and name it header_view.php, in the document add all the following code.<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title> <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/css/style.css" /> </head> <body> <div id="wrapper">
<div id="footer"> © 2011 <a href="http://tutsforweb.blogspot.com/">TutforWeb</a> All Rights Reserved. </div><!-- <div class="footer">--> </div><!--<div id="wrapper">--> </body> </html>
I will use the tableless form design. It has some benefits:
1.Faster loading of pages
2.Efficiency
3.Consistency
4.SEO advantage
5.Layouts and design sophistication
6.Bandwidth efficiency
Create a blank document in the views file (application -> views) and name it registration_view.php, in the document add all the following code.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
<?php echo form_open("user/login"); ?>
<label for="email">Email:</label>
<input type="text" id="email" name="email" value="" />
<label for="password">Password:</label>
<input type="password" id="pass" name="pass" value="" />
<input type="submit" class="" value="Sign in" />
<?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<div class="reg_form">
<div class="form_title">Sign Up</div>
<div class="form_sub_title">It's free and anyone can join</div>
<?php echo validation_errors('<p class="error">'); ?>
<?php echo form_open("user/registration"); ?>
<p>
<label for="user_name">User Name:</label>
<input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" />
</p>
<p>
<label for="email_address">Your Email:</label>
<input type="text" id="email_address" name="email_address" value="<?php echo set_value('email_address'); ?>" />
</p>
<p>
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="<?php echo set_value('password'); ?>" />
</p>
<p>
<label for="con_password">Confirm Password:</label>
<input type="password" id="con_password" name="con_password" value="<?php echo set_value('con_password'); ?>" />
</p>
<p>
<input type="submit" class="greenButton" value="Submit" />
</p>
<?php echo form_close(); ?>
</div><!--<div class="reg_form">-->
</div><!--<div id="content">--><?php echo validation_errors('<p>'); ?>
In our input fields, we use the below function.
<?php echo set_value('user_name'); ?>
Because of above function the original data will be show in the form, if there is an error after the validation rules. So we have only been dealing with errors.
Below code is thank_view.php and welcome_view.php.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
<?php echo form_open("user/login"); ?>
<label for="email">Email:</label>
<input type="text" id="email" name="email" value="" />
<label for="pass">Password:</label>
<input type="password" id="pass" name="pass" value="" />
<input type="submit" class="" value="Sign in" />
<?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<h1>Thank!</h1>
</div><!--<div id="content">--><div class="content">
<h2>Welcome Back, <?php echo $this->session->userdata('username'); ?>!</h2>
<p>This section represents the area that only logged in members can access.</p>
<h4><?php echo anchor('user/logout', 'Logout'); ?></h4>
</div><!--<div class="content">-->@charset "utf-8";
/* CSS Document */
body{
background-color:#FFF;
font-family:Monaco,Consolas,'Lucida Grande','Lucida Console';
font-size:16px;
text-shadow:rgba(0,0,0,0.01) 0 0 0;
}
#wrapper{
width:960px;
margin:0 auto;
}
#content{
width:960px;
margin:5px;
float:left;
}
/************************************************/
.signup_wrap{
height:25px;
width:100%;
padding:5px;
background-color:#2A1FFF;
}
.signin_form{
float:right;
}
.signin_form input{
width:80px;
}
.reg_form{
width:460px;
padding:20px;
margin:0 auto;
border:3px solid #DFDFDF;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbd4e5));
background: -moz-linear-gradient(top, #fff, #cbd4e5);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff', endColorstr='#cbd4e5');
}
.form_title,
.form_sub_title{
font-size:20px;
font-family:"Lucida Grande",Tahoma,Verdana,Arial,sans-serif;
font-size:20px;
font-weight:bold;
}
.form_sub_title{
font-weight:normal;
padding:6px 0 15px 0;
}
.reg_form p{
width: 300px;
clear: left;
margin: 0;
padding: 5px 0 8px 0;
padding-left: 155px; /*width of left column containing the label elements*/
border-top: 1px dashed gray;
height: 1%;
}
.reg_form label{
font-weight: bold;
float: left;
margin-left: -155px; /*width of left column*/
width: 150px; /*width of labels. Should be smaller than left column (155px) to create some right margin*/
}
input{
padding:3px;
color:#333333;
border:1px solid #96A6C5;
margin-top:2px;
width:180px;
font-size:11px;
}
.greenButton{
width:auto;
margin:10px 0 0 2px;
padding:3px 4px 3px 4px;
color:white;
background-color:#589d39;
outline:none;
border:1px solid #006600;
font-weight:bold;
}
.greenButton:active{
background-color:#006600;
padding:4px 3px 2px 5px;
}
.error{
color:#F00;
}
#footer{
color:#fff;
padding-top:20px;
text-align:center;
background: #454546;
height: 20px;
clear:both;
}
In the next tutorial we will discuss jQuery Ajax with CI.
Download Source Code
GREAT Stuff about Jquery, I wanted to add autocomplete and calendar controls and I found your website very helpful. thanks a lot
ReplyDeleteI would add the autocomplete on EDDM Printing and if there is any problem will definitely come back for help
thanks!!!
thanks, it works
ReplyDeleteError Number: 1062
ReplyDeleteDuplicate entry 'myemail@email.com' for key 'email'
when email filed is unique on DB.
Thats deadly, thanks
ReplyDeleteVery nice
ReplyDeletewhen i run the this code with my url path
ReplyDeletehttp://localhost/ci/index.php/user
i got an error like this.
Parse error: syntax error, unexpected 'function_construct' (T_STRING), expecting variable (T_VARIABLE) in C:\xampp\htdocs\ci\application\controllers\user.php on line 4
my code ruin properly but i am able to seen registration page it's show me....
ReplyDeleteWelcome Back, !
This section represents the area that only logged in members can access.
Logout
Nice tutorial, thanks!
ReplyDeleteOne question: after registering the user is sent to the thank page. When refreshing the thank page in the browser, the browser asks if the form should be sent again. That shouldn't happen, I think. How do I prevent the browser from asking this?
Superb and easy to digest.
ReplyDeleteThanks! You really saved my time! good tutorial
ReplyDeleteThank you sir for such a good tutorial it really saved my time and efforts. i appreciate your work.
ReplyDeletethanks
Don’t hesitate to ask him, if something goes wrong on our side.
ReplyDeletebut where is her reply ???????
I m facing this Problem.
if you can solve please send the answer to info@WorldQuotes.in
Not Found
The requested URL /ci_user/index.php/user/registration was not found on this server.
very good tutorial.Really helped me
ReplyDeleteOnly thing I think this tut is missing would be the idea of making sure the new user is unique. In a normal application of this we do not want users with the same username / email .
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI am beginner to CI,I have done all the thing said above , "Welcome to CodeIgniter!" is my home page now what to do..?
ReplyDeleteHi, one quick question.
ReplyDeleteDoes this code protect against SQL injection?
Great and Easy tutoria for all
ReplyDeleteGreat, thanks it works.......
ReplyDeleteBrilliant post, although only minor issue with it, when you are displaying the user as logged in, it should be
ReplyDeletesession->userdata('user_name'); ?>
Thank you anyway!
great tutorial, provide a jump start for me to learn CI
ReplyDelete