CodeIgniter 4 is the latest version of the popular PHP framework. It is a powerful and lightweight framework that can be used to create web applications quickly and easily. In this tutorial, we will show you how to create a simple user authentication system using CodeIgniter 4.
We will be creating a registration and login system with CodeIgniter 4. We will also be using the authentication library provided by CodeIgniter 4 to handle user authentication.
Step 1: Setup CodeIgniter 4
The first step is to setup CodeIgniter 4 on your server. You can download the latest version of CodeIgniter 4 from the official website. Once you have downloaded the zip file, extract it and upload it to your server.
Step 2: Create Database
Next, we need to create a database for our application. We will be using MySQL for this tutorial. Create a new database and name it “ci4_auth”.
Step 3: Configure Database
Now, we need to configure the database for our application. Open the “app/Config/Database.php” file and update the database configuration as follows:
$db[‘default’] = array(
‘dsn’ => ”,
‘hostname’ => ‘localhost’,
‘username’ => ‘root’,
‘password’ => ”,
‘database’ => ‘ci4_auth’,
‘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
);
Step 4: Create User Table
Next, we need to create a table for storing user information. We will be using the “migrations” feature of CodeIgniter 4 to create the table.
Create a new file in the “app/Database/Migrations” folder and name it “001_create_users_table.php”. Open the file and add the following code:
forge->addField([
‘id’ => [
‘type’ => ‘INT’,
‘constraint’ => 11,
‘unsigned’ => TRUE,
‘auto_increment’ => TRUE
],
‘name’ => [
‘type’ => ‘VARCHAR’,
‘constraint’ => ‘100’,
],
’email’ => [
‘type’ => ‘VARCHAR’,
‘constraint’ => ‘100’,
],
‘password’ => [
‘type’ => ‘VARCHAR’,
‘constraint’ => ‘255’,
],
‘created_at’ => [
‘type’ => ‘DATETIME’,
‘null’ => TRUE,
],
‘updated_at’ => [
‘type’ => ‘DATETIME’,
‘null’ => TRUE,
],
]);
$this->forge->addKey(‘id’, TRUE);
$this->forge->createTable(‘users’);
}
//——————————————————————–
public function down()
{
$this->forge->dropTable(‘users’);
}
}
Step 5: Create Model
Next, we need to create a model for our application. Create a new file in the “app/Models” folder and name it “UserModel.php”. Open the file and add the following code:
setRules([
‘name’ => ‘required|min_length[3]’,
’email’ => ‘required|valid_email|is_unique[users.email]’,
‘password’ => ‘required|min_length[8]’,
]);
if (!$validation->run()) {
return redirect()->to(‘/register’)->withInput()->with(‘errors’, $validation->getErrors());
}
// Create the user
$userModel = new UserModel();
$userModel->save([
‘name’ => $this->request->getVar(‘name’),
’email’ => $this->request->getVar(’email’),
‘password’ => $this->request->getVar(‘password’),
]);
// Redirect to login page
return redirect()->to(‘/login’);
}
public function login()
{
// Validate the input
$validation = \Config\Services::validation();
$validation->setRules([
’email’ => ‘required|valid_email’,
‘password’ => ‘required’,
]);
if (!$validation->run()) {
return redirect()->to(‘/login’)->withInput()->with(‘errors’, $validation->getErrors());
}
// Authenticate the user
$userModel = new UserModel();
$user = $userModel->where(’email’, $this->request->getVar(’email’))->first();
if (!$user) {
return redirect()->to(‘/login’)->withInput()->with(‘errors’, [‘Invalid email or password’]);
}
if (!password_verify($this->request->getVar(‘password’), $user[‘password’])) {
return redirect()->to(‘/login’)->withInput()->with(‘errors’, [‘Invalid email or password’]);
}
// Login the user
$session = \Config\Services::session();
$session->set(‘user’, $user);
// Redirect to home page
return redirect()->to(‘/’);
}
public function logout()
{
// Logout the user
$session = \Config\Services::session();
$session->remove(‘user’);
// Redirect to login page
return redirect()->to(‘/login’);
}
}
Step 7: Create Views
Finally, we need to create the views for our application. Create a new folder in the “app/Views” folder and name it “auth”.
Create a new file in the “app/Views/auth” folder and name it “register.php”. Open the file and add the following code:
Register
0): ?>
Create a new file in the “app/Views/auth” folder and name it “login.php”. Open the file and add the following code:
Login
0): ?>
Step 8: Setup Routes
Finally, we need to setup the routes for our application. Open the “app/Config/Routes.php” file and add the following routes:
$routes->get(‘register’, ‘Auth::register’);
$routes->post(‘register’, ‘Auth::register’);
$routes->get(‘login’, ‘Auth::login’);
$routes->post(‘login’, ‘Auth::login’);
$routes->get(‘logout’, ‘Auth::logout’);
Conclusion
In this tutorial, we have created a simple user authentication system using CodeIgniter 4. We have used the authentication library provided by CodeIgniter 4 to handle user authentication. We have also used the migrations feature of CodeIgniter 4 to create the user table.
To create login and registration form in codeigniter 4. In this tutorial, you will learn how to create simple login and registration system in codeigniter with database.
This codeigniter 4 login and registration with session example will guide you step by step on how to build registration and login system in codeigniter 4 app.
How To Create A Registration/Signup and Login System in CodeIgniter 4
By using the following steps, you can create signup/registration and login authencation system in codeIgniter 4 projects:
- Step 1: Setup Codeigniter Project
- Step 2: Basic Configurations
- Step 3: Create Database With Table
- Step 4: Setup Database Credentials
- Step 5: Create Controllers
- Step 6: Create Model File
- Step 7: Create Views
- Step 8: Create Authentication File
- Step 9: Start Development server
Step 1: Setup Codeigniter Project
In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”
Step 2: Basic Configurations
In this step, you need set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3: Create Database With Table
In this step, you need to create a database name demo, so open PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a users table in your database.
CREATE TABLE users(
user_id INT PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(100),
user_email VARCHAR(100),
user_password VARCHAR(200),
user_created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;
Step 4: Setup Database Credentials
In this step, you need to connect app to the database. so, you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'demo',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
Next, make a connection between the database and the CodeIgniter app.
So, find the env file in the codeigniter app root, then rename it to .env and open the file.
Then find the following code:
# database.default.hostname = localhost
# database.default.database = ci4
# database.default.username = root
# database.default.password = root
# database.default.DBDriver = MySQLi
Change it to be like the following:
database.default.hostname = localhost
database.default.database = login_db
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
Next, find the following code:
# CI_ENVIRONMENT = production
Then change it to be like the following:
CI_ENVIRONMENT = development
That means you enter development mode, this mode will help you make it easier to track errors as you build your project.
Step 5: Create Controller
Now Go to app/Controllers and create a controller name Register.php. And add the following methods into Register.php controller file:
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\UserModel;
class Register extends Controller
{
public function index()
{
//include helper form
helper(['form']);
$data = [];
echo view('register', $data);
}
public function save()
{
//include helper form
helper(['form']);
//set rules validation form
$rules = [
'name' => 'required|min_length[3]|max_length[20]',
'email' => 'required|min_length[6]|max_length[50]|valid_email|is_unique[users.user_email]',
'password' => 'required|min_length[6]|max_length[200]',
'confpassword' => 'matches[password]'
];
if($this->validate($rules)){
$model = new UserModel();
$data = [
'user_name' => $this->request->getVar('name'),
'user_email' => $this->request->getVar('email'),
'user_password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
];
$model->save($data);
return redirect()->to('/login');
}else{
$data['validation'] = $this->validator;
echo view('register', $data);
}
}
}
Again open app/Controllers and create a controller name Login.php. And add the following methods into Login.php controller file:
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\UserModel;
class Login extends Controller
{
public function index()
{
helper(['form']);
echo view('login');
}
public function auth()
{
$session = session();
$model = new UserModel();
$email = $this->request->getVar('email');
$password = $this->request->getVar('password');
$data = $model->where('user_email', $email)->first();
if($data){
$pass = $data['user_password'];
$verify_pass = password_verify($password, $pass);
if($verify_pass){
$ses_data = [
'user_id' => $data['user_id'],
'user_name' => $data['user_name'],
'user_email' => $data['user_email'],
'logged_in' => TRUE
];
$session->set($ses_data);
return redirect()->to('/dashboard');
}else{
$session->setFlashdata('msg', 'Wrong Password');
return redirect()->to('/login');
}
}else{
$session->setFlashdata('msg', 'Email not Found');
return redirect()->to('/login');
}
}
public function logout()
{
$session = session();
$session->destroy();
return redirect()->to('/login');
}
}
After that, create another Controller file called “Dashboard.php” inside “app/Controllers” directory and add the following code into it:
<?php namespace App\Controllers;
use CodeIgniter\Controller;
class Dashboard extends Controller
{
public function index()
{
$session = session();
echo "Welcome back, ".$session->get('user_name');
}
}
Step 6: Create Model File
In this step, only one model file is needed, namely “UserModel.php“.
Create a model file named “UserModel.php” in the “app/Models” directory, then type the following code:
<?php namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model{
protected $table = 'users';
protected $allowedFields = ['user_name','user_email','user_password','user_created_at'];
}
Step 7: Create Views
In this step, you need to create some views file for login, reigstration and dashboard view. So, visit application/views/ directory and create login.php, register.php file.
First of all, create login.php inside application/views directory and add the following code into it:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
<title>Login</title>
</head>
<body>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-6">
<h1>Sign In</h1>
<?php if(session()->getFlashdata('msg')):?>
<div class="alert alert-danger"><?= session()->getFlashdata('msg') ?></div>
<?php endif;?>
<form action="/login/auth" method="post">
<div class="mb-3">
<label for="InputForEmail" class="form-label">Email address</label>
<input type="email" name="email" class="form-control" id="InputForEmail" value="<?= set_value('email') ?>">
</div>
<div class="mb-3">
<label for="InputForPassword" class="form-label">Password</label>
<input type="password" name="password" class="form-control" id="InputForPassword">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
<!-- Popper.js first, then Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
</body>
</html>
Then create register.php inside application/views directory and add the following code into it:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
<title>Register</title>
</head>
<body>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-6">
<h1>Sign Up</h1>
<?php if(isset($validation)):?>
<div class="alert alert-danger"><?= $validation->listErrors() ?></div>
<?php endif;?>
<form action="/register/save" method="post">
<div class="mb-3">
<label for="InputForName" class="form-label">Name</label>
<input type="text" name="name" class="form-control" id="InputForName" value="<?= set_value('name') ?>">
</div>
<div class="mb-3">
<label for="InputForEmail" class="form-label">Email address</label>
<input type="email" name="email" class="form-control" id="InputForEmail" value="<?= set_value('email') ?>">
</div>
<div class="mb-3">
<label for="InputForPassword" class="form-label">Password</label>
<input type="password" name="password" class="form-control" id="InputForPassword">
</div>
<div class="mb-3">
<label for="InputForConfPassword" class="form-label">Confirm Password</label>
<input type="password" name="confpassword" class="form-control" id="InputForConfPassword">
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
<!-- Popper.js first, then Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/popper[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
</body>
</html>
Step 8: Create Authentication File
In this step, you need to protect the function index() on the “Dashboard.php” Controller from users who have not logged in using Filter.
So, visit “app/Filters” directory and create a filter file named “Auth.php“. Then add the following code into it:
<?php namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class Auth implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
// if user not logged in
if(! session()->get('logged_in')){
// then redirct to login page
return redirect()->to('/login');
}
}
//--------------------------------------------------------------------
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}
After that, open the “Filters.php” file located in the “app/Config” folder, then find the following code:
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
];
Then change it to be like this:
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
'auth' => \App\Filters\Auth::class,
];
Next, open the “Routes.php” file located in the “app/Config” folder, then find the following code:
$routes->get('/', 'Home::index');
$routes->get('/dashboard', 'Dashboard::index',['filter' => 'auth']);
Step 9: Start Development server
Now, open your terminal and execute the following command to start this app:
Then open your browser and hit the following url on it:
http://localhost:8080/register
Conclusion
Codeigniter 4 login and registration example. In this tutorial, you have learn how to create login and registration system in codeigniter 4.
Recommended Codeigniter Posts
If you have any questions or thoughts to share, use the comment form below to reach us.