Building a User Authentication System in CodeIgniter : Day 5

5 1

Welcome back to Day 5 Building a User Authentication System in CodeIgniter of our journey to build a portfolio website with CodeIgniter! Today, we’re diving into one of the fundamental aspects of web development: user authentication. By the end of this tutorial, you’ll have a solid understanding of how to implement user registration, login, and logout functionalities using CodeIgniter.

So Start Learning Building a User Authentication System in CodeIgniter

Why User Authentication Matters

User authentication is crucial for web applications that require restricted access or personalized user experiences. It ensures that only authorized users can access certain parts of the website and helps maintain data security.

Setting Up User Authentication

Step 1: Create the Users Table

  1. Database Setup: If you haven’t already, ensure your users table is set up in your MySQL database. You can refer to Day 3 for guidance on creating the users table structure.

Step 2: Create Controller and Views

  1. Controller: Navigate to application/controllers/ and create a new file named Auth.php. Add the following code:
<?php
class Auth extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->library('form_validation');
        $this->load->library('session');
    }
    
    public function register() {
        // Validation rules
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[50]|is_unique[users.username]');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
        $this->form_validation->set_rules('password_confirm', 'Password Confirmation', 'required|matches[password]');
        
        if ($this->form_validation->run() === FALSE) {
            $this->load->view('register');
        } else {
            $this->user_model->register();
            $this->session->set_flashdata('success_msg', 'Registration successful. Please login.');
            redirect('auth/login');
        }
    }
    
    public function login() {
        // Validation rules
        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');
        
        if ($this->form_validation->run() === FALSE) {
            $this->load->view('login');
        } else {
            $user = $this->user_model->login();
            if ($user) {
                $user_data = array(
                    'user_id' => $user['id'],
                    'username' => $user['username'],
                    'logged_in' => TRUE
                );
                $this->session->set_userdata($user_data);
                redirect('dashboard'); // Replace 'dashboard' with your desired redirect page
            } else {
                $this->session->set_flashdata('error_msg', 'Invalid username or password.');
                redirect('auth/login');
            }
        }
    }
    
    public function logout() {
        $this->session->unset_userdata('user_id');
        $this->session->unset_userdata('username');
        $this->session->unset_userdata('logged_in');
        $this->session->sess_destroy();
        redirect('auth/login');
    }
}
?>
  1. Views: Create register.php and login.php files in application/views/auth/ directory. These views will contain the HTML forms for user registration and login.
    • register.php
<h2>Register</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('auth/register'); ?>
    <input type="text" name="username" placeholder="Username" /><br />
    <input type="email" name="email" placeholder="Email" /><br />
    <input type="password" name="password" placeholder="Password" /><br />
    <input type="password" name="password_confirm" placeholder="Confirm Password" /><br />
    <button type="submit">Register</button>
</form>
  • login.php
<h2>Login</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('auth/login'); ?>
    <input type="text" name="username" placeholder="Username" /><br />
    <input type="password" name="password" placeholder="Password" /><br />
    <button type="submit">Login</button>
</form>

Step 3: Create Model

  1. Model: Create user_model.php in application/models/ directory. Add the following code to handle database operations:
<?php
class User_model extends CI_Model {
    public function register() {
        $data = array(
            'username' => $this->input->post('username'),
            'email' => $this->input->post('email'),
            'password_hash' => password_hash($this->input->post('password'), PASSWORD_DEFAULT)
        );
        return $this->db->insert('users', $data);
    }
    
    public function login() {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        
        $this->db->where('username', $username);
        $user = $this->db->get('users')->row_array();
        
        if ($user && password_verify($password, $user['password_hash'])) {
            return $user;
        } else {
            return false;
        }
    }
}
?>

Testing Authentication

  1. Access the Registration Page: Open your web browser and go to http://localhost/your_project_name/index.php/auth/register. Fill out the registration form and submit.
  2. Access the Login Page: After registering, go to http://localhost/your_project_name/index.php/auth/login. Use your registered username and password to log in.
  3. Logout: Create a logout link in your application where users can log out of their accounts.

Conclusion

Congratulations! You’ve successfully implemented a basic user authentication system using CodeIgniter. This feature allows users to register, log in, and log out of your portfolio website. In Day 6, we’ll start designing the homepage and integrating user-specific features.

Compalgo Labs offering School Management Software : Setting Up the Database

Feel free to leave any questions or comments below. Keep practicing and exploring CodeIgniter! Happy coding!

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *