CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New
Need a Website Or Web Application Contact : +91 9437911966 (Whatsapp) Note: Paid Service

Codeigniter 4 login signup


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;

Connect to Database

Find the env file in the project root, then rename it to .env and open the file.

.env

database.default.hostname = localhost
database.default.database = login_db
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi

UserModel.php

<?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'];
 }

Create a Controller Register.php, in the "app/Controllers" folder

Register.php

<?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);
        }
         
    }
 
}

Create a View register.php File, in the "app/Views" folder

Register.php

<!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.js@1.16.0/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>

Create a Controller Login.php, in the "app/Controllers" folder

Login.php

<?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');
     }
 } 

Create a Controller Dashboard.php, in the "app/Views" folder

Dashboard.php

<?php namespace App\Controllers;
 
 use CodeIgniter\Controller;
  
 class Dashboard extends Controller
 {
     public function index()
     {
         $session = session();
         echo "Welcome back, ".$session->get('user_name');
     }
 }

Register.php and Login.php Controllers, create another Controller file called "Dashboard.php" in the "app/Controllers" folder

Dashboard.php

<?php namespace App\Controllers;
 
use CodeIgniter\Controller;
 
class Dashboard extends Controller
{
    public function index()
    {
        $session = session();
        echo "Welcome back, ".$session->get('user_name');
    }
}

Create a Filters Auth.php in the "app/Filters" folder

Auth.php

<?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 */
     }
 }

Filters.php file located in the "app/Config" folder

Filters.php

public $aliases = [
      'csrf'     => \CodeIgniter\Filters\CSRF::class,
      'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
      'honeypot' => \CodeIgniter\Filters\Honeypot::class,
      'auth'     => \App\Filters\Auth::class,
];

Routes.php file located in the "app/Config" folder

Routes.php

$routes->get('/', 'Home::index');
$routes->get('/dashboard', 'Dashboard::index',['filter' => 'auth']);