Codeigniter Login and Registration Tutorial & Source Code

.env setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file.

Now we are ready to use environment variables.

Register & Login HTML files

These are the HTML files of Register and Login pages, in register.html

Setting Up CodeIgniter & Connecting to Database

For setting up CodeIgniter, you should download the latest version of CodeIgniter. As of writing this article I’m using CodeIgniter version of 3.1.6.

After downloading extract it in a separate directory on your server. Access this directory in the browser you should see a screen like this.

Making HTML forms as CodeIgniter Forms

Instead of Using HTML forms, we can use the CodeIgniter form library previously I’ve loaded form helper.

Adding Form Validation to Register & Login

For adding form validations in CodeIgniter, I’m using CodeIgniter’s form validation library.

Application controller settings

Next we need to create application controller.

Application routes configuration

To configure application routes, we need to open up the file /app/Config/Routes.php. This is the main routes config file where we will do all routes of application.

Inside this we will have login & registration routes.

//...

$routes->match(['get', 'post'], 'register', 'User::register', ['filter' => 'noauth']);
$routes->match(['get', 'post'], 'login', 'User::login', ['filter' => 'noauth']);
$routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']);
$routes->get('profile', 'User::profile', ['filter' => 'auth']);
$routes->get('logout', 'User::logout');

//...

Inside these routes, we are using filters. Filters are the sections from where we can check every request to application and do action. We will create two filters – Auth & Noauth.

Let’s create Model.

Application testing

Open project into terminal and start development server.

$ php spark serve

Open these urls to see the action.

Codeigniter 4 installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Now, let’s configure database and application connectivity.

Codeigniter login and registration source code:

Download Source

Read Also:

Complete code of all the files

If you have any problem arraning above pieces of code, you can use this complete code.[sociallocker]

Configuring codeigniter 4 filters

Filters in CodeIgniter 4 are just like guards. They detect request and process what we have created it for. So here, we will create and configure two different filters which we use in application.

To create filters, we will use the folder inside app directory i.e /app/Filters.

$ php spark make:filter Auth

It will create file Auth.php at /app/Filters

$ php spark make:filter Noauth

It will create Noauth.php at /app/Filters

Successfully, we have created filters. Next, we need to configure into application so that we will able to use.

To register these filters. Open up the file – /app/Config/Filters.php

As, you can see we have added our filter config lines

‘auth’ => AppFiltersAuth::class,‘noauth’ => AppFiltersNoauth::class,

Create controller

Now we need to create a controller name Auth.php. In this controller we will create some method/function. We will build some of the methods like :

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Form_model');
$this->load->library(array('form_validation','session'));
$this->load->helper(array('url','html','form'));
$this->user_id = $this->session->userdata('user_id');
}
public function index()
{
$this->load->view('login');
}
public function post_login()
{
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_message('required', 'Enter %s');
if ($this->form_validation->run() === FALSE)
{  
$this->load->view('login');
}
else
{   
$data = array(
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password')),
);
$check = $this->Form_model->auth_check($data);
if($check != false){
$user = array(
'user_id' => $check->id,
'email' => $check->email,
'first_name' => $check->first_name,
'last_name' => $check->last_name
);
$this->session->set_userdata($user);
redirect( base_url('dashboard') ); 
}
$this->load->view('login');
}
}	
public function post_register()
{
$this->form_validation->set_rules('first_name', 'First Name', 'required');
$this->form_validation->set_rules('last_name', 'Last Name', 'required');
$this->form_validation->set_rules('contact_no', 'Contact No', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_message('required', 'Enter %s');
if ($this->form_validation->run() === FALSE)
{  
$this->load->view('register');
}
else
{   
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'mobile_number' => $this->input->post('contact_no'),
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password')),
);
$check = $this->Form_model->insert_user($data);
if($check != false){
$user = array(
'user_id' => $check,
'email' => $this->input->post('email'),
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
);
}
$this->session->set_userdata($user);
redirect( base_url('auth/dashboard') ); 
}
}
public function logout(){
$this->session->sess_destroy();
redirect(base_url('auth'));
}	
public function dashboard(){
if(empty($this->user_id)){
redirect(base_url('auth'));
}
$this->load->view('dashboard');
}
}

Create database table

Next, we need a table. That table will be responsible to store data.

Похожее:  Личный кабинет налоговой ФНС: инструкция по регистрации и входу для физических лиц (налогоплательщиков) и юридических лиц

Let’s create a table with some columns.

Create parent template

Create a folder layouts inside /app/Views. Inside layouts create a file app.php. This is be parent layout.

Open file /app/Views/layouts/app.php and write this code.

We will extend this template file to every view file and dynamically attach page views in it’s body.

Create views

Now we need to create register.php, go to application/views/ folder and create register.php file. Here put the below html code for showing registration form.

<html>
<head>
<link rel="stylesheet" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<title>Sign Up</title>
</head>
<style type="text/css">
body {
background-color: #F3EBF6;
font-family: 'Ubuntu', sans-serif;
}
div.error {
margin-bottom: 15px;
margin-top: -6px;
margin-left: 58px;
color: red;
}
.main {
background-color: #FFFFFF;
width: 400px;
height: 620px;
margin: 7em auto;
border-radius: 1.5em;
box-shadow: 0px 11px 35px 2px rgba(0, 0, 0, 0.14);
}
.sign {
padding-top: 40px;
color: #8C55AA;
font-family: 'Ubuntu', sans-serif;
font-weight: bold;
font-size: 23px;
}
.un {
width: 76%;
color: rgb(38, 50, 56);
font-weight: 700;
font-size: 14px;
letter-spacing: 1px;
background: rgba(136, 126, 126, 0.04);
padding: 10px 20px;
border: none;
border-radius: 20px;
outline: none;
box-sizing: border-box;
border: 2px solid rgba(0, 0, 0, 0.02);
margin-bottom: 50px;
margin-left: 46px;
text-align: center;
margin-bottom: 27px;
font-family: 'Ubuntu', sans-serif;
}
form.form1 {
padding-top: 40px;
}
.pass {
width: 76%;
color: rgb(38, 50, 56);
font-weight: 700;
font-size: 14px;
letter-spacing: 1px;
background: rgba(136, 126, 126, 0.04);
padding: 10px 20px;
border: none;
border-radius: 20px;
outline: none;
box-sizing: border-box;
border: 2px solid rgba(0, 0, 0, 0.02);
margin-bottom: 50px;
margin-left: 46px;
text-align: center;
margin-bottom: 27px;
font-family: 'Ubuntu', sans-serif;
}
.un:focus, .pass:focus {
border: 2px solid rgba(0, 0, 0, 0.18) !important;
}
.submit {
cursor: pointer;
border-radius: 5em;
color: #fff;
background: linear-gradient(to right, #9C27B0, #E040FB);
border: 0;
padding-left: 40px;
padding-right: 40px;
padding-bottom: 10px;
padding-top: 10px;
font-family: 'Ubuntu', sans-serif;
margin-left: 35%;
font-size: 13px;
box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.04);
}
.forgot {
text-shadow: 0px 0px 3px rgba(117, 117, 117, 0.12);
color: #E1BEE7;
padding-top: 15px;
}
button {
text-shadow: 0px 0px 3px rgba(117, 117, 117, 0.12);
color: #E1BEE7;
text-decoration: none
}
@media (max-width: 600px) {
.main {
border-radius: 0px;
}
</style>
<body>
<div class="main">
<p class="sign" align="center">Sign Up</p>
<form action="<?php echo base_url('auth/post_register') ?>" method="post" accept-charset="utf-8">
<input class="un " type="text" align="center" name="first_name" placeholder="first name">
<?php echo form_error('first_name'); ?>   
<input class="un " type="text" align="center" name="last_name" placeholder="last name">
<?php echo form_error('last_name'); ?>  
<input class="un " type="text" align="center" name="contact_no" placeholder="contact number" maxlength="10">
<?php echo form_error('contact_no'); ?> 
<input class="un " type="text" align="center" name="email" placeholder="email">
<?php echo form_error('email'); ?> 
<input class="pass" type="password" align="center" name="password" placeholder="Password">
<?php echo form_error('password'); ?> 
<button type="submit" align="center" class="submit">Sign Up</button>
</form>                
</div>
</body>
</html>

Now we need to create views for showing login form also showing dashbaord. So now create first view name login.php and put the below html in this file.

<html>
<head>
<link rel="stylesheet" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<title>Sign in</title>
</head>
<style type="text/css">
body {
background-color: #F3EBF6;
font-family: 'Ubuntu', sans-serif;
}
div.error {
margin-bottom: 15px;
margin-top: -6px;
margin-left: 58px;
color: red;
}
.main {
background-color: #FFFFFF;
width: 400px;
height: 400px;
margin: 7em auto;
border-radius: 1.5em;
box-shadow: 0px 11px 35px 2px rgba(0, 0, 0, 0.14);
}
.sign {
padding-top: 40px;
color: #8C55AA;
font-family: 'Ubuntu', sans-serif;
font-weight: bold;
font-size: 23px;
}
.un {
width: 76%;
color: rgb(38, 50, 56);
font-weight: 700;
font-size: 14px;
letter-spacing: 1px;
background: rgba(136, 126, 126, 0.04);
padding: 10px 20px;
border: none;
border-radius: 20px;
outline: none;
box-sizing: border-box;
border: 2px solid rgba(0, 0, 0, 0.02);
margin-bottom: 50px;
margin-left: 46px;
text-align: center;
margin-bottom: 27px;
font-family: 'Ubuntu', sans-serif;
}
form.form1 {
padding-top: 40px;
}
.pass {
width: 76%;
color: rgb(38, 50, 56);
font-weight: 700;
font-size: 14px;
letter-spacing: 1px;
background: rgba(136, 126, 126, 0.04);
padding: 10px 20px;
border: none;
border-radius: 20px;
outline: none;
box-sizing: border-box;
border: 2px solid rgba(0, 0, 0, 0.02);
margin-bottom: 50px;
margin-left: 46px;
text-align: center;
margin-bottom: 27px;
font-family: 'Ubuntu', sans-serif;
}
.un:focus, .pass:focus {
border: 2px solid rgba(0, 0, 0, 0.18) !important;
}
.submit {
cursor: pointer;
border-radius: 5em;
color: #fff;
background: linear-gradient(to right, #9C27B0, #E040FB);
border: 0;
padding-left: 40px;
padding-right: 40px;
padding-bottom: 10px;
padding-top: 10px;
font-family: 'Ubuntu', sans-serif;
margin-left: 35%;
font-size: 13px;
box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.04);
}
.forgot {
text-shadow: 0px 0px 3px rgba(117, 117, 117, 0.12);
color: #E1BEE7;
padding-top: 15px;
}
button {
text-shadow: 0px 0px 3px rgba(117, 117, 117, 0.12);
color: #E1BEE7;
text-decoration: none
}
@media (max-width: 600px) {
.main {
border-radius: 0px;
}
</style>
<body>
<div class="main">
<p class="sign" align="center">Sign in</p>
<form action="<?php echo base_url('auth/post_login') ?>" method="post" accept-charset="utf-8">
<input class="un " type="text" align="center" name="email" placeholder="email">
<?php echo form_error('email'); ?> 
<input class="pass" type="password" align="center" name="password" placeholder="Password">
<?php echo form_error('password'); ?> 
<button type="submit" align="center" class="submit">Sign in</button>
</form>                
</div>
</body>
</html>

Dashboard view file

Create dashboard.php

Source code of /app/Views/dashboard.php

Enable development mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Похожее:  Куфар Личный кабинет — Вход и регистрация

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

How to create login and registration in codeigniter – web preparations

Dear Reader, let us we know that “How to Create Login and Registration in Codeigniter with Live Demo“ So in this Tutorial, We Learn Step By Step Login and Registration Process.

In any website or Blog Login and Registration are a very important factor which plays a very important role in managing website.In any website, Blog or Portal want to store information about users and when any user want his information in future then we need to save his information for this we need to create Registration.

Login is also very important for authentication of users are valid are not and manage users information user wise.So lets start Login and Registration Creation…

At first we see Live Demo by click on bellow Demo button

We assumed that you have already Configure Codeigniter if you don’t configure then don’t worry, you need to Configure Codeigniter at first here

and if you already Configure then you don’t need to Configure again

Step 1:- At very first you need to create users table in your database for storing information of users. for creating table create a database and run bellow SQLquery in your database

Step 2:- Now you need to Libraries and helper in autoload.php which is located in

your_project_nameapplicationconfig

like

ci_demoapplicationconfig

Step 3:- At first you need to create Users.phpController which is located in

your_project_nameapplicationcontrollers

like

ci_demoapplicationcontrollers

after creation Users.php Controller paste the below code

Step 4:- Now create User.phpModel which is located in

your_project_nameapplicationmodels

like

ci_demoapplicationmodels

after the creation of User.php Model paste the below code

Step 5:- Now create users folder in views which is located in

your_project_nameapplicationviews

like

ci_demoapplicationviews

Create registration.php in users folder and paste the below code

Step 6:- Create login.php in users folder and paste the below code

Step 7:- Create account.php in users folder and paste the below code

Step 8:- Create a assets folder in your project and create CSS folder in the assets folder

your_project_name/assets/css

like

ci_demo/assets/css

Now create a style.css file in css folder and paste the below code

step 9:- Now open your Browser run your project as

localhost/your_project_name/users/registration you can see the result as below snapshot

how-to-create-login-and-registration-in-codeigniter-step-1

step 10:- Now fill all required details and click submit button

you can see the result that your registration was successful as below snapshot

how-to-create-login-and-registration-in-codeigniter-step-2

step 11:- After Registration for login fill email and password click submit button

how-to-create-login-and-registration-in-codeigniter-step-3

step 12:- After Authentication successfully you will be redirected your profile as below snapshot

Codeigniter Login and Registration Tutorial & Source Code

step 13:- if you want to log out your profile you need to click on Logout you will be redirected login page as you can see in below snapshot

how-to-create-login-and-registration-in-codeigniter-step-3

Congratulations you have successfully created Registration and Login in Codeigniter, if you have any query then contact us or comment below, Thanks

Loading url helper

Open BaseController.php from /app/Controllers folder. Search for $helpers, inside this helpers array simply add this url helper.

protected $helpers = [‘url’];

This url helper will load base_url() and site_url() functions.

Also we have the option to load any helper directly to any controller using helper() function.

Login view file

Create login.php

Source code for /app/Views/login.php

Profile page

Create profile.php

Source code of /app/Views/profile.php

Register view file

Add registration view file. File with the name of register.php

Code of /app/Views/register.php

Setup database credentials

In this step, We need to connect our project to database. we need to go application/config/ and open database.php file in text editor. After open the file in text editor, We need to setup database credential in this file like below.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

View file setup in application

View files generally created inside /app/Views. We need view files for login, register, profile, dashboard etc.

Let’s create those step by step.

You may like

  1. Registrtion form validation using jquery validator
  2. jQuery Form Validation Custom Error Message
  3. jQuery AJAX Form Submit PHP MySQL
  4. Simple Registration Form in PHP with Validation
  5. jQuery Ajax Form Submit with FormData Example
  6. Laravel 6 Ajax Form Submit With Validation Tutorial
  7. Google ReCaptcha Form Validation in laravel
  8. Laravel 6 | jQuery Form Validation Tutorial with Demo Example
  9. Form Validation Example In Laravel 6
  10. Codeigniter php jQuery Ajax Form Submit with Validation

If you have any questions or thoughts to share, use the comment form below to reach us.

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (Пока оценок нет)
Загрузка...

Добавить комментарий

Ваш адрес email не будет опубликован.

Adblock
detector