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');
}
No comments:
Post a Comment