Login Api in php CI with authentication

First, create a controller called Auth.php in your CodeIgniter application’s controllers directory:


defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller {

    public function __construct() {
        $this->load->model('user_model'); // Load user model

    public function login() {
        $email = $this->input->post('email');
        $password = $this->input->post('password');

        // Check if user exists
        $user = $this->user_model->get_by_email($email);
        if (!$user) {
            // User not found
            $response = array('message' => 'Invalid email or password');

        // Verify password
        if (!password_verify($password, $user->password)) {
            // Invalid password
            $response = array('message' => 'Invalid email or password');

        // Password is correct, create JWT token
        $payload = array(
            'user_id' => $user->id,
            'email' => $user->email,
        $token = JWT::encode($payload, 'your_secret_key');

        // Return token in response
        $response = array('token' => $token);

  1. In the above code, we’re first loading the user_model which we’ll use to check if the user exists and verify the password.

  2. Then, in the login function, we’re getting the email and password from the request body.

  3. We’re using the get_by_email function of the user_model to check if the user with the given email exists. If the user doesn’t exist, we’re returning a 401 Unauthorized status code with an error message.

  4. If the user exists, we’re verifying the password using password_verify function. If the password is incorrect, we’re returning a 401 status code with an error message.

  5. If the email and password are correct, we’re creating a JSON Web Token (JWT) using the JWT::encode function (assuming you have installed the firebase/php-jwt library via Composer). We’re encoding the user’s ID and email into the token’s payload.

  6. Finally, we’re returning the JWT token in the response body.

Note: You need to install Firebase JWT library. You can do this by running the following command via Composer:

					composer require firebase/php-jwt




Leave a Reply

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