Are you looking to build a secure user authentication system for your web application? In this comprehensive, step-by-step tutorial, you will learn how to implement a complete login and authentication system using CodeIgniter. Whether you are building a new project from scratch or enhancing an existing application, this guide walks you through setting up controllers, configuring database models, managing user sessions, and validating credentials securely so you can protect your app against unauthorized access.
Step 1 Create Table
CREATE TABLE
`adminmaster` (
`ID` int(11) NOT NULL,
`Name` varchar(50) NOT NULL,
`UserName` varchar(50) NOT NULL,
`Pass` varchar(255) NOT NULL,
`RStatus` tinyint(4) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;
Password is encrypted with
$password = "ghsrapicsm12";
$hash = password_hash($password, PASSWORD_DEFAULT);
You can use plain password as per your requirement
Step 2 Create Login Form
<form
action="<?=
site_url('login')
?>"
method="post">
<?=
csrf_field() ?>
Username
<input
type="text"
name="Username"
placeholder="Username"
required=""><br>
Password
<input type="password"
name="Pass"
placeholder="Password"
required="">
<input type="submit" Value="Login">
</form>
Step 3 Create Model
class UserModel extends Model
{
protected $table = 'adminmaster';
protected $primaryKey = 'ID';
protected $allowedFields = ['Username', 'Pass'];
protected $returnType = 'array';
}
Step 4 Routes
$routes->get('login', 'Home::login');
$routes->post('login', 'Login::LoginUser');
Step 5 Login Controller
public function LoginUser()
{
if ($this->request->getMethod() === 'POST')
{
$uname = $this->request->getPost('Username');
$password = $this->request->getPost('Pass');
$userModel = new UserModel();
$user = $userModel->where('Username', $uname)->first();
if ($user && password_verify($password, $user['Pass'])) {
session()->set([
'UID' => $user['ID'],
'Username' => $user['UserName'],
'logged_in' => true
]);
return redirect()->to('/dashboard');
}
return redirect()->back()->with('error', 'Invalid Username or password');
}
return redirect()->to('login');
}
After successful login create your own rout where you want to go. this code will jump you to dashboard . So if you using same code then create routes
$routes->get('dashboard', 'Admin::dashboard');
Step 6 : Logout
$routes->get('logout', 'Login::logout');
<a href="<?= site_url('logout') ?>">Sign Out</a>
Controller
public function logout()
{
session()->destroy();
return redirect()->to('/klskjfUjs62543jd');
}
Step 7 : Authenticate Page access
Go to App>Filters folder and create a file AuthFilter.php
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class AuthFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (! session()->get('logged_in')) {
return redirect()->to('/login');
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// nothing here
}
}
After create this file open Filters.php in app>Config Folder. and add 'auth' => \App\Filters\AuthFilter::class,
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
'auth' => \App\Filters\AuthFilter::class,
];
Thats all . Now you can use ['filter' => 'auth'] in any Routes which you want to be access after login like this
$routes->get('dashboard', 'Admin::index', ['filter' => 'auth']);
$routes->get('logout', 'Login::logout', ['filter' => 'auth']);

No comments:
Post a Comment