0% found this document useful (0 votes)
188 views16 pages

CodeIgniter 4 User Login & Registration Guide

Uploaded by

infodztarabich
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
188 views16 pages

CodeIgniter 4 User Login & Registration Guide

Uploaded by

infodztarabich
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

How To Make User Login And Registration In CodeIgniter 4

binaryboxtuts.com/php-tutorials/how-to-make-user-login-and-registration-in-codeigniter-4

Binarytuts August 12, 2021

Most of the web apps today that has users or different types of users requires login or authentication
to safeguard the functionalities and data information of the system. And today, I will show you how to
make a user login and registration in CodeIgniter 4.

CodeIgniter is one of the most powerful PHP frameworks. It is an open-source web framework that is
used for rapid web development. It is popular for its exceptional performance, small footprint,
requires nearly zero configuration, thorough documentation and many more.

If you want to learn more about CodeIgniter, you can check and read their documentation.

Now we proceed to show you how to make user login and registration in CodeIgniter 4:

Tutorial Video:

Step 1: Install CodeIgniter 4


For us to install CodeIgniter 4 we can install via composer or directly download CodeIgniter 4 here:

Install via composer:

1 composer create-project codeigniter4/appstarter ci-4-user-login-registration

Step 2: Change CodeIgniter Environment

1/16
The default environment of CodeIgniter is production, it is a safety feature to add security in case
settings are messed up when it goes live. For us to change the environment we will rename or copy
the file env to .env. Once it is renamed, open the file and uncomment and change the
CI_ENVIRONMENT value from production to development.

.env

1 CI_ENVIRONMENT = development

Step 3: Configure Database


After setting up the environment, we will then configure our database. You can configure it on .env or
on the config file located at app/Config/Database.php. For this tutorial we will configure it on
app/Config/Database.php.

Configure the database connection values:

app/Config/Database.php.

1 <?php
2 namespace Config;
3 use CodeIgniter\Database\Config;
4 class Database extends Config
5 {
6 public $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
7 public $defaultGroup = 'default';
8 public $default = [
9 'DSN' => '',
10 'hostname' => 'localhost',
11 'username' => 'root',
12 'password' => '',
13 'database' => 'ci_4_login_register',
14 'DBDriver' => 'MySQLi',
15 'DBPrefix' => '',
16 'pConnect' => false,
17 'DBDebug' => (ENVIRONMENT !== 'production'),
18 'charset' => 'utf8',
19 'DBCollat' => 'utf8_general_ci',
20 'swapPre' => '',
21 'encrypt' => false,
22 'compress' => false,
23 'strictOn' => false,
24 'failover' => [],
25 'port' => 3306,
26 ];
27 public $tests = [
28 'DSN' => '',
29 'hostname' => '127.0.0.1',
30 'username' => '',
31 'password' => '',
32 'database' => ':memory:',
33 'DBDriver' => 'SQLite3',
34 'DBPrefix' => 'db_',
35 'pConnect' => false,
36 'DBDebug' => (ENVIRONMENT !== 'production'),
37 'charset' => 'utf8',
38 'DBCollat' => 'utf8_general_ci',
39 'swapPre' => '',
40 'encrypt' => false,

2/16
41 'compress' => false,
42 'strictOn' => false,
43 'failover' => [],
44 'port' => 3306,
45 ];
46 public function __construct()
47 {
48 parent::__construct();
49 if (ENVIRONMENT === 'testing')
{
50
$this->defaultGroup = 'tests';
51 }
52 }
53 }
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

Step 4: Create A Model and Migration


Model – it a class that represents a database table.

3/16
Migration – like version control for the database that allows us to modify and share database
schema to your team.

Execute this command on the Terminal or CMD to create a model:

1 php spark make:model UserModel

open the created model at app/Models/UserModel.php. Inside the file you can see configuration
options, you can read the documentation to further learn about its configuration options. We will now
update the configs:

app/Models/UserModel.php

1 <?php
2 namespace App\Models;
3 use CodeIgniter\Model;
4 class UserModel extends Model
5 {
6 protected $DBGroup = 'default';
7 protected $table = 'users';
8 protected $primaryKey = 'id';
9 protected $useAutoIncrement = true;
10 protected $insertID = 0;
11 protected $returnType = 'array';
12 protected $useSoftDeletes = false;
13 protected $protectFields = true;
14 protected $allowedFields = ['email', 'password'];
15 protected $useTimestamps = true;
16 protected $dateFormat = 'datetime';
17 protected $createdField = 'created_at';
18 protected $updatedField = 'updated_at';
19 protected $deletedField = 'deleted_at';
20 protected $validationRules = [];
21 protected $validationMessages = [];
22 protected $skipValidation = false;
23 protected $cleanValidationRules = true;
24 protected $allowCallbacks = true;
25 protected $beforeInsert = [];
26 protected $afterInsert = [];
27 protected $beforeUpdate = [];
28 protected $afterUpdate = [];
29 protected $beforeFind = [];
30 protected $afterFind = [];
31 protected $beforeDelete = [];
32 protected $afterDelete = [];
33 }
34
35
36
37
38
39
40
41
42

After creating the model, we will then create a migration file.

Execute this command on the Terminal or CMD to create a migration:

4/16
1 php spark make:migration AddUser

Open the created migration file on app/Database/Migrations/ and paste these codes:

1 <?php
2 namespace App\Database\Migrations;
3 use CodeIgniter\Database\Migration;
4 class AddUser extends Migration
5 {
6 public function up()
7 {
$this->forge->addField([
8
'id' => [
9
'type' => 'BIGINT',
10
'constraint' => 255,
11
'unsigned' => true,
12
'auto_increment' => true
13
],
14 'email' => [
15
'type' => 'VARCHAR',
16
'unique' => true,
17
'constraint' => '255',
18 ],
19 'password' => [
20 'type' => 'VARCHAR',
21 'constraint' => '255',
22 ],
23 'created_at' => [
24 'type' => 'TIMESTAMP',
25 'null' => true
26 ],
27 'updated_at' => [
28 'type' => 'TIMESTAMP',
29 'null' => true
30 ],
31 ]);
32 $this->forge->addPrimaryKey('id');
33 $this->forge->createTable('users');
}
34
public function down()
35
{
36 $this->forge->dropTable('users');
37 }
38 }
39
40
41
42
43
44

Run the migration by executing the migrate command:

1 php spark migrate

Step 5: Create Controllers


A Controller is the one responsible for receiving Request and returning Response.

Execute this command on the Terminal or CMD to create a the Controllers:

5/16
1 php spark make:controller Login
2 php spark make:controller Register
3 php spark make:controller Dashboard

After executing the command, it will create files located at app/Controllers. Open those file and
insert these codes:

app/Controllers/Login.php

1 <?php
2 namespace App\Controllers;
3 use App\Controllers\BaseController;
4 use App\Models\UserModel;
5 class Login extends BaseController
6 {
7 public function index()
8 {
9 return view('login');
}
10
11
public function authenticate()
12
{
13
$session = session();
14
$userModel = new UserModel();
15
$email = $this->request->getVar('email');
16 $password = $this->request->getVar('password');
17
18
$user = $userModel->where('email', $email)->first();
19 if(is_null($user)) {
20 return redirect()->back()->withInput()->with('error', 'Invalid username or
21 password.');
22 }
23 $pwd_verify = password_verify($password, $user['password']);
24 if(!$pwd_verify) {
25 return redirect()->back()->withInput()->with('error', 'Invalid username or
26 password.');
27 }
28 $ses_data = [
29 'id' => $user['id'],
30 'email' => $user['email'],
31 'isLoggedIn' => TRUE
32 ];
$session->set($ses_data);
33
return redirect()->to('/dashboard');
34
35
36 }
37
public function logout() {
38 session_destroy();
39 return redirect()->to('/login');
40 }
41 }
42
43
44
45
46
47
48
49
50
51

6/16
app/Controllers/Register.php

1 <?php
2 namespace App\Controllers;
3 use App\Controllers\BaseController;
4 use App\Models\UserModel;
5 class Register extends BaseController
6 {
7 public function __construct(){
8 helper(['form']);
}
9
public function index()
10
{
11 $data = [];
12
return view('register', $data);
13 }
14
15 public function register()
16 {
17 $rules = [
18 'email' => ['rules' =>
19 'required|min_length[4]|max_length[255]|valid_email|is_unique[users.email]'],
20 'password' => ['rules' => 'required|min_length[8]|max_length[255]'],
21 'confirm_password' => [ 'label' => 'confirm password', 'rules' =>
22 'matches[password]']
23 ];
24
25 if($this->validate($rules)){
26 $model = new UserModel();
27 $data = [
28 'email' => $this->request->getVar('email'),
29 'password' => password_hash($this->request->getVar('password'),
30 PASSWORD_DEFAULT)
];
31 $model->save($data);
32
return redirect()->to('/login');
33 }else{
34 $data['validation'] = $this->validator;
35 return view('register', $data);
36 }
37
38 }
39 }
40
41
42
43
44

app/Controllers/Dashboard.php

7/16
1 <?php
2 namespace App\Controllers;
3 use App\Controllers\BaseController;
4 class Dashboard extends BaseController
5 {
6 public function index()
7 {
8 return view('dashboard');
}
9 }
10
11
12
13

Step 6: Create Controller Filters


Controller Filters are classes that allows us to perform actions before or after the controllers execute.

We create 2 controller filter:

authFilter – to filter authenticated users


guestFilter – to filter unauthenticated users

Execute this command on the Terminal or CMD to create a the Filters:

1 php spark make:filter AuthFilter


2 php spark make:filter GuestFilter

After executing the command, it will create files located at app/Filters. Open those file and insert
these codes:

app/Filters/AuthFilter.php

8/16
1 <?php
2 namespace App\Filters;
3 use CodeIgniter\Filters\FilterInterface;
4 use CodeIgniter\HTTP\RequestInterface;
5 use CodeIgniter\HTTP\ResponseInterface;
6 class AuthFilter implements FilterInterface
7 {
8 public function before(RequestInterface $request, $arguments = null)
9 {
10 if (!session()->get('isLoggedIn'))
{
11
return redirect()->to('/login');
12
}
13 }
14 public function after(RequestInterface $request, ResponseInterface $response,
15 $arguments = null)
16 {
17 }
18 }
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

app/Filters/GuestFilter.php

9/16
1 <?php
2 namespace App\Filters;
3 use CodeIgniter\Filters\FilterInterface;
4 use CodeIgniter\HTTP\RequestInterface;
5 use CodeIgniter\HTTP\ResponseInterface;
6 class GuestFilter implements FilterInterface
7 {
8 public function before(RequestInterface $request, $arguments = null)
9 {
10 if (session()->get('isLoggedIn'))
{
11
return redirect()->to('/dashboard');
12
}
13 }
14 public function after(RequestInterface $request, ResponseInterface $response,
15 $arguments = null)
16 {
17 }
18 }
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

After creating the filters, we must add it to filters config located at app/Config/Filters.php. We will
creating an alias for our filters.

app/Config/Filters.php

10/16
1 public $aliases = [
2 'csrf' => CSRF::class,
3 'toolbar' => DebugToolbar::class,
4 'honeypot' => Honeypot::class,
5 'authFilter' => \App\Filters\AuthFilter::class,
6 'guestFilter' => \App\Filters\GuestFilter::class,
7 ];

Step 7: Register Routes


Open the config file for routing located at app/Config/Routes.php and register these routes:

1 $routes->setDefaultController('Register');
2 $routes->get('/', 'Register::index', ['filter' => 'guestFilter']);
3 $routes->get('/register', 'Register::index', ['filter' => 'guestFilter']);
4 $routes->post('/register', 'Register::register', ['filter' => 'guestFilter']);
5 $routes->get('/login', 'Login::index', ['filter' => 'guestFilter']);
6 $routes->post('/login', 'Login::authenticate', ['filter' => 'guestFilter']);
7 $routes->get('/logout', 'Login::logout', ['filter' => 'authFilter']);
8 $routes->get('/dashboard', 'Dashboard::index', ['filter' => 'authFilter']);
9
10
11
12
13
14
15

Step 8: Create View Files


View files are web page or fragments of a page like header or footer and etc. Views can be
embedded to other views whenever you need hierarchy on view files.

We will create out view files in this path app/Views.

layout.php
login.php
register.php
dashboard.php

After creating the view files, Insert the code below:

app/Views/layout.php

11/16
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>CodeIgniter Login and Register</title>
<link
5 href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
6 rel="stylesheet" integrity="sha384-
7 EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
8 crossorigin="anonymous">
9 <script
10 src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
11 integrity="sha384-
MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
</head>
<body>
<?= $this->renderSection("content"); ?>
<body>
</html>

app/Views/login.php

1 <?=$this->extend("layout")?>
2
3 <?=$this->section("content")?>
4
5 <div class="container">
<div class="row justify-content-md-center mt-5">
6 <div class="col-4">
7 <div class="card">
8 <div class="card-body">
9 <h5 class="card-title mb-4">Sign In</h5>
10 <?php if(session()->getFlashdata('error')):?>
11 <div class="alert alert-danger">
12 <?= session()->getFlashdata('error') ?>
13 </div>
<?php endif;?>
14
<form action="<?php echo base_url('/login'); ?>" method="post">
15 <div class="mb-3">
16
<label for="email" class="form-label">Email address</label>
17 <input type="email" class="form-control" id="email" name="email">
18 </div>
19 <div class="mb-3">
20 <label for="password" class="form-label">Password</label>
21 <input type="password" class="form-control" id="password" name="password">
22 </div>
23 <div class="d-grid gap-2">
24 <button type="submit" class="btn btn-primary btn-block">Login</button>
25 <p class="text-center">Don't have account? <a href="<?php echo base_url('/'); ?
26 >">Register here</a><p>
27 </div>
</form>
28 </div>
29 </div>
30 </div>
31 </div>
32
33 </div>
34
35 <?=$this->endSection()?>
36
37

app/Views/register.php

12/16
1 <?=$this->extend("layout")?>
2
3 <?=$this->section("content")?>
4
5 <div class="container">
<div class="row justify-content-md-center mt-5">
6 <div class="col-4">
7 <div class="card">
8 <div class="card-body">
9 <h5 class="card-title mb-4">Register</h5>
10 <form action="<?php echo base_url('/register'); ?>" method="post">
11 <div class="mb-3">
12 <label for="email" class="form-label">Email address</label>
13 <input type="email" class="form-control" id="email" name="email" value="<?=
14 set_value('email') ?>">
15 <?php if(isset($validation)):?>
16 <small class="text-danger"><?= $validation->getError('email') ?></small>
<?php endif;?>
17 </div>
18 <div class="mb-3">
19 <label for="password" class="form-label">Password</label>
20 <input type="password" class="form-control" id="password" name="password">
21 <?php if(isset($validation)):?>
22 <small class="text-danger"><?= $validation->getError('password') ?></small>
23 <?php endif;?>
24 </div>
25 <div class="mb-3">
26 <label for="confirm_password" class="form-label">Confirm Password</label>
27 <input type="password" class="form-control" id="confirm_password"
28 name="confirm_password">
<?php if(isset($validation)):?>
29 <small class="text-danger"><?= $validation->getError('confirm_password') ?>
30 </small>
31 <?php endif;?>
32 </div>
33 <div class="d-grid gap-2">
34 <button type="submit" class="btn btn-primary btn-block">Register Now</button>
35 <p class="text-center">Have already an account <a href="<?php echo
36 base_url('/login'); ?>">Login here</a><p>
37 </div>
</form>
38
</div>
39 </div>
40 </div>
41 </div>
42
43 </div>
44
45 <?=$this->endSection()?>

app/Views/dashboard.php

13/16
1 <?=$this->extend("layout")?>
2
3 <?=$this->section("content")?>
4
5 <div class="container">
<div class="row justify-content-md-center mt-5">
6 <div class="col-12">
7 <nav class="navbar navbar-expand-lg navbar-light bg-light">
8 <div class="container-fluid">
9 <a class="navbar-brand" href="#">Dashboard</a>
10 <div class="d-flex">
11 <ul class="navbar-nav">
12 <li class="nav-item">
13 <a class="nav-link " aria-current="page" href="<?php echo base_url('/logout'); ?
14 >">Logout</a>
15 </li>
</ul>
16 </div>
17 </div>
18 </nav>
19 <h2 class="text-center mt-5">User Dashboard</h2 >
20 </div>
21 </div>
22
23 </div>
24
25 <?=$this->endSection()?>
26

Step 8: Run the Application


Now that we have completed the steps above we will now run the app. To run the app, execute this
command:

1 php spark serve

Open this URL in your browser and now you can test:

1 http://localhost:8080

Results:
Login Page

14/16
Register Page

Dashboard Page

15/16
16/16

You might also like