Login and Registration Forms in CodeIgniter 3 and MySQL
In this topic, we will create a simple registration and login system in CodeIgniter 3. We will use email id as the login id. There will be a simple home page with options for Signup and Login. Complete the registration by entering the name, email_id and password. Once registration is successful, the customer can login into the application. We will use CodeIgniter 3 and MySQL to develop this application.
Create a MySQL table for customer details
We will create a table named 'customer' in the MySQL database. The table structure is given below:
Table: customer
This table stores details of all customers who completed registration successfully.
Below are the columns in this table.
id - It is the primary key and auto-incremented
name - Name of the customer
email - Email Id of the customer
password - Password for login
MySQL create table script for this table is given below.
customer.sql
CREATE TABLE `customer` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `customer`
ADD PRIMARY KEY (`id`);
ALTER TABLE `customer`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
Create the views for Home, Signup and Login Pages
There are three views for the home page (home.php), signup page (signup.php) and login page (login.php). Additionally, there will be a custom css file and a small piece of JavaScript for showing/hiding the password in the login page. Let us take a look at them one by one.
View for Home Page
Our home page is simple, it just displays two links, one for signup and the other for login. When the customer is logged in, it will display a welcome message with the name of the customer and a logout link. Below are the screens for before login and after login:
If session data is set, it displays "Welcome" with the customer name. If session data is not available, it displays two links - Signup and Login.
View for Signup Page
The Signup or Registration page displays a form for the customer to fill out and submit. It has name, email id, password and confirm password fields. Then a submit button. See the below code for the signup page:
In the <form> action, it calls signup() method of the customer controller. For each input field validations are done in the Controller and the validation message for each input gets displayed just below the input field in the form.
View for Login Page
The login page will have email_id and password as input fields. For each input, an error message will be displayed in case the validation fails. In <form> action, it calls login() method of the controller. See below code for the login view:
We will use a JavaScript function for the option "Show Password" which is added as a checkbox in the login form. When the user clicks on it, it calls a JavaScript function togglePwd() defined in scripts.js.
Below is the code for togglePwd() function:
scripts.js
function togglePwd() {
var pwd = document.getElementById("password");
if (pwd.type === "password")
pwd.type = "text";
else
pwd.type = "password";
}
This function changes the type of the password field in the login page, from "password" to "text" and vice versa.
Let me give the stylesheet also I am using for all these views.
I just added a few simple styles here, you can always add better styles.
So, our views are done, now let's go to the controller section.
Controller code (CustomerController.php)
Our controller function has an index() method to display the home page, signup() method to display and process the signup form, login() method for customer login and a logout() method.
Controller method index()
index() method is executed by default in a controller. In this method, it just loads the view that displays home page.
public function index(){
$this->load->view('home');
}
Controller Method signup()
It writes CodeIgniter 3 validation rules for each input field in the form. If validation fails for a field, it reloads the view with an error message displayed corresponding to the field for which validation failed. Let's see the code for signup() method.
public function signup() {
$element = [];
$element['succ_msg'] = "";
$element['err_msg'] = "";
if (isset($_POST['signup'])) {
// get the values of form fields
$name = $this->input->post('name');
$email = $this->input->post('email');
$password = $this->input->post('password');
$password = md5($password);
// validate each field
$this->form_validation->set_rules('name', 'Name', 'trim|required',
array(
'required'=>'You must provide a %s')
);
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[customer.email]',
array(
'required'=>'You must provide an %s',
'valid_email' => 'This is not a valid email address',
'is_unique' => 'This %s already registered')
);
$this->form_validation->set_rules('password', 'Password', 'trim|required',
array(
'required' => 'You must provide %s')
);
$this->form_validation->set_rules('conf_pwd', 'Confirm Password', 'trim|required|matches[password]',
array(
'required' => 'You must provide %s',
'matches' => 'Passwords do not match')
);
if ($this->form_validation->run() == FALSE) {
// validation not passed, so load the form again
$this->load->view('signup',$element);
}
else {
// validations are successful, go for signup
$data = array('name'=>$name, 'email'=>$email, 'password'=>$password);
$result = $this->ModelCustomer->signup($data);
if ($result){
$msg = 'Signup successful, please <a href="'.base_url().'login">login</a> with your email id and password';
$element['succ_msg'] = $msg;
}
else{
$msg = "Error in Signup";
$element['err_msg'] = $msg;
}
$this->load->view('signup',$element);
}
}
else {
$this->load->view('signup', $element);
}
} // end of function signup
Validations are performed on the input data using form_validation->set_rules() method. For details on how to do form validation in CodeIgniter 3, you can read the topic How to do Form Validation in CodeIgniter 3.
For successful validation of all fields, it calls Model method signup() which inserts the signup details into a database table and then the registration is complete.
Controller Method login()
Method login() is called when the user clicks on the Login link in the Home page. This method does some validation and then checks with database to see if the credentials match. If a match is found, it sets the email and name in the session and redirects the user to the home page, otherwise, it reloads the login view with the error message. Let's see the code:
public function login(){
$data = [];
$data['msg'] = "";
if (isset($_POST['login'])) {
$email = $this->input->post('email');
$password = $this->input->post('password');
// validate fields
$this->form_validation->set_rules('email', 'Email Id', 'trim|required',
array(
'required'=>'You must provide an %s')
);
$this->form_validation->set_rules('password', 'Password', 'trim|required',
array(
'required'=>'You must provide a %s')
);
if ($this->form_validation->run() == FALSE) {
// validation not passed, so load the form again
$this->load->view('login', $data);
}
else {
$result = $this->ModelCustomer->check_user($email, $password);
if ($result) {
$sess_array = [];
$sess_array = [
'email' => $result->email,
'name' => $result->name,
];
$this->session->set_userdata('login', $sess_array);
redirect(base_url(),"refresh");
}
else {
$msg = "Invalid login credentials";
$data['msg'] = $msg;
$this->load->view('login', $data);
}
}
}
else {
$this->load->view('login', $data);
}
} // end of function login
It sets session data for email and name using an array $sess_array[] and redirects the user to the home page.
Controller Method logout()
Method logout() deletes the session and redirects the user to home page. See below:
public function logout() {
$this ->session ->sess_destroy();
redirect(base_url(),"refresh");
}
So, these were our controller methods, now let's see the Model methods in next step.
The Model (ModelCustomer.php)
The Customer Model has two methods, one for signup and the other for login. For signup, the model method name is signup(). This method takes the input data in an array and uses $db->insert() method to insert a row in the customer table. For login, you have seen, check_user() method is used. So now let's see the code for these methods in the model:
Model Method signup()
function signup($data) {
if (!empty($data)) {
$result = $this->db->insert('customer', $data);
return $result;
}
}
Our views, controller and model are developed. Now we need to do some setup/configuration changes in CodeIgniter before we run the application. Let's do that in the next step.
Configuration files and Test the Application
We will update the below files in the config folder and we will also have our .htaccess file in the root directory. See below:
Using URL rewriting rule, it redirects all request except those which are not existing files or directories.
Test The Application
Make sure in your XAMPP control panel Apache server and MySQL services are running. Open the browser and run localhost/customer. You will see the home page displayed. Click on Signup and do a successful registration. Then using the email and password as given during registration, try to login. You should be able to login successfully and see the message displayed on the screen with the name and logout link. Also, test the validation for signup and login.
Note:
For simplicity, I have not enforced any password rule in the signup form. You should add at least some minimum requirement for password, maybe a minimum length can be given.
Conclusion
Developing registration and login forms in CodeIgniter 3 can help you understand CodeIgniter 3 if you have just started working with it. Creating the views, writing Controller functions, form validations and database select-insert statements, quite a few areas you have to code for. This gives you a better understanding of how CodeIgniter 3 works.
Post a Comment