User Login and Registration with CodeIgniter REST API

The RESTful web services provide a simple way to exchange data between different applications. If your web application needs to communicate over the across platforms, RESTful web service needs to be developed. The application can connect and work with different platforms (web, mobile, etc) using RESTful API. The REST API uses GET, PUT, POST and DELETE HTTP request for data handling across platforms.

CodeIgniter RESTful web service is the easiest way to integrate REST API service in the web application. Using CodeIgniter Rest Server you can easily create the REST API in CodeIgniter. In this tutorial, we will show you how to implement user login and registration with CodeIgniter REST API.
The example code will demonstrate how to build REST API and handle the user authentication (login and registration) with CodeIgniter.

The following steps will be implemented to create REST API in CodeIgniter.

  • Setup Rest Server in CodeIgniter.
  • Create API method to handle user login via POST request.
  • Create API method to handle user registration via POST request.
  • Create API method to fetch the user account data via GET request.
  • Create API method to update the user information via PUT request.
  • Interact with the CodeIgniter RESTful API.

Before getting started, take a look the files structure of CodeIgniter REST application.

codeigniter-rest-api-login-system-files-structure-codexworld

Create Database Tables

To store user’s account information, a table needs to be created in the database. The following SQL creates a users table with some basic fields in MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `phone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive ',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates a keys table to store REST API key for authentication.

CREATE TABLE `keys` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `key` varchar(40) NOT NULL,
 `level` int(2) NOT NULL,
 `ignore_limits` tinyint(1) NOT NULL DEFAULT '0',
 `is_private_key` tinyint(1) NOT NULL DEFAULT '0',
 `ip_addresses` text,
 `date_created` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Import the API key data in the keys table, which will be used to validate the API call.

INSERT INTO `keys` (`id`, `user_id`, `key`, `level`, `ignore_limits`, `is_private_key`, `ip_addresses`, `date_created`) VALUES
(NULL, 1, 'CODEX@123', 0, 0, 0, NULL, '2018-10-11 13:34:33');

CodeIgniter REST Controller Setup

We will use REST Controller library to build RESTful web services in CodeIgniter. Follow the below steps to integrate RESTful server in CodeIgniter using REST Controller library.

  • Place the REST configuration file (rest.php) in application/config/ folder and specify the API configurations.
    • Enable REST API authentication.
      $config['rest_auth'] = 'basic';
    • Set the username and password for API authentication.
      $config['rest_valid_logins'] = ['admin' => '1234'];
    • Set the table name that holds the API key.
      $config['rest_keys_table'] = 'keys';
    • Enable REST API key.
      $config['rest_enable_keys'] = TRUE;
  • Place the CodeIgniter Rest Controller library (REST_Controller.php) in the application/libraries/ folder.
  • Place the CodeIgniter Format library (Format.php) in the application/libraries/ folder.
  • Place the Rest Controller’s language (rest_controller_lang.php) in the application/language/english/ folder for multilingual support.

Note that: All the required files are included in the source code, you don’t need to download these files separately.

Model (User.php)

The User model handles the database related operations (fetch, insert, update, and delete).

  • __construct()
    • Load the database library.
    • Specify the table name to be used.
  • getRows() – Fetch the data from the database based on the given condition and returns data as an array.
  • insert() – Insert the data in the database.
  • update() – Update the data based on the ID in the database.
  • delete() – Delete data based on the ID from the database.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class 
User extends CI_Model {

    public function 
__construct() {
        
parent::__construct();
        
        
// Load the database library
        
$this->load->database();
        
        
$this->userTbl 'users';
    }

    
/*
     * Get rows from the users table
     */
    
function getRows($params = array()){
        
$this->db->select('*');
        
$this->db->from($this->userTbl);
        
        
//fetch data by conditions
        
if(array_key_exists("conditions",$params)){
            foreach(
$params['conditions'] as $key => $value){
                
$this->db->where($key,$value);
            }
        }
        
        if(
array_key_exists("id",$params)){
            
$this->db->where('id',$params['id']);
            
$query $this->db->get();
            
$result $query->row_array();
        }else{
            
//set start and limit
            
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
                
$this->db->limit($params['limit'],$params['start']);
            }elseif(!
array_key_exists("start",$params) && array_key_exists("limit",$params)){
                
$this->db->limit($params['limit']);
            }
            
            if(
array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
                
$result $this->db->count_all_results();    
            }elseif(
array_key_exists("returnType",$params) && $params['returnType'] == 'single'){
                
$query $this->db->get();
                
$result = ($query->num_rows() > 0)?$query->row_array():false;
            }else{
                
$query $this->db->get();
                
$result = ($query->num_rows() > 0)?$query->result_array():false;
            }
        }

        
//return fetched data
        
return $result;
    }
    
    
/*
     * Insert user data
     */
    
public function insert($data){
        
//add created and modified date if not exists
        
if(!array_key_exists("created"$data)){
            
$data['created'] = date("Y-m-d H:i:s");
        }
        if(!
array_key_exists("modified"$data)){
            
$data['modified'] = date("Y-m-d H:i:s");
        }
        
        
//insert user data to users table
        
$insert $this->db->insert($this->userTbl$data);
        
        
//return the status
        
return $insert?$this->db->insert_id():false;
    }
    
    
/*
     * Update user data
     */
    
public function update($data$id){
        
//add modified date if not exists
        
if(!array_key_exists('modified'$data)){
            
$data['modified'] = date("Y-m-d H:i:s");
        }
        
        
//update user data in users table
        
$update $this->db->update($this->userTbl$data, array('id'=>$id));
        
        
//return the status
        
return $update?true:false;
    }
    
    
/*
     * Delete user data
     */
    
public function delete($id){
        
//update user from users table
        
$delete $this->db->delete('users',array('id'=>$id));
        
//return the status
        
return $delete?true:false;
    }

}

Controller (Authentication.php)

It’s always better to make a separate folder for API related controller. In this example, we will place the API controller in controllers/api/ folder.
The Authentication API controller handles the API requests. It allows to implement a RESTful interface for the user login and registration through the GET, POST, and PUT request.

  • __construct() – Load the User model to work with the database.
  • login_post()
    • Retrieve the login data from the POST request.
    • Validate login through the database using getRows() method of the User model.
    • Set the response and exit.
  • registration_post()
    • Retrieve the registration data from the POST request.
    • Validate and insert user data in the database using insert() method of the User model.
  • user_get()
    • Fetch the user data from the database using getRows() method of the User model.
    • It returns a single user data if the ID is specified, otherwise, all users data.
    • Set the response and exit.
  • user_put()
    • Retrieve the user ID and data from the PUT request.
    • Update the user data in the database based on the ID.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

// Load the Rest Controller library
require APPPATH '/libraries/REST_Controller.php';

class 
Authentication extends REST_Controller {

    public function 
__construct() { 
        
parent::__construct();
        
        
// Load the user model
        
$this->load->model('user');
    }
    
    public function 
login_post() {
        
// Get the post data
        
$email $this->post('email');
        
$password $this->post('password');
        
        
// Validate the post data
        
if(!empty($email) && !empty($password)){
            
            
// Check if any user exists with the given credentials
            
$con['returnType'] = 'single';
            
$con['conditions'] = array(
                
'email' => $email,
                
'password' => md5($password),
                
'status' => 1
            
);
            
$user $this->user->getRows($con);
            
            if(
$user){
                
// Set the response and exit
                
$this->response([
                    
'status' => TRUE,
                    
'message' => 'User login successful.',
                    
'data' => $user
                
], REST_Controller::HTTP_OK);
            }else{
                
// Set the response and exit
                //BAD_REQUEST (400) being the HTTP response code
                
$this->response("Wrong email or password."REST_Controller::HTTP_BAD_REQUEST);
            }
        }else{
            
// Set the response and exit
            
$this->response("Provide email and password."REST_Controller::HTTP_BAD_REQUEST);
        }
    }
    
    public function 
registration_post() {
        
// Get the post data
        
$first_name strip_tags($this->post('first_name'));
        
$last_name strip_tags($this->post('last_name'));
        
$email strip_tags($this->post('email'));
        
$password $this->post('password');
        
$phone strip_tags($this->post('phone'));
        
        
// Validate the post data
        
if(!empty($first_name) && !empty($last_name) && !empty($email) && !empty($password)){
            
            
// Check if the given email already exists
            
$con['returnType'] = 'count';
            
$con['conditions'] = array(
                
'email' => $email,
            );
            
$userCount $this->user->getRows($con);
            
            if(
$userCount 0){
                
// Set the response and exit
                
$this->response("The given email already exists."REST_Controller::HTTP_BAD_REQUEST);
            }else{
                
// Insert user data
                
$userData = array(
                    
'first_name' => $first_name,
                    
'last_name' => $last_name,
                    
'email' => $email,
                    
'password' => md5($password),
                    
'phone' => $phone
                
);
                
$insert $this->user->insert($userData);
                
                
// Check if the user data is inserted
                
if($insert){
                    
// Set the response and exit
                    
$this->response([
                        
'status' => TRUE,
                        
'message' => 'The user has been added successfully.',
                        
'data' => $insert
                    
], REST_Controller::HTTP_OK);
                }else{
                    
// Set the response and exit
                    
$this->response("Some problems occurred, please try again."REST_Controller::HTTP_BAD_REQUEST);
                }
            }
        }else{
            
// Set the response and exit
            
$this->response("Provide complete user info to add."REST_Controller::HTTP_BAD_REQUEST);
        }
    }
    
    public function 
user_get($id 0) {
        
// Returns all the users data if the id not specified,
        // Otherwise, a single user will be returned.
        
$con $id?array('id' => $id):'';
        
$users $this->user->getRows($con);
        
        
// Check if the user data exists
        
if(!empty($users)){
            
// Set the response and exit
            //OK (200) being the HTTP response code
            
$this->response($usersREST_Controller::HTTP_OK);
        }else{
            
// Set the response and exit
            //NOT_FOUND (404) being the HTTP response code
            
$this->response([
                
'status' => FALSE,
                
'message' => 'No user was found.'
            
], REST_Controller::HTTP_NOT_FOUND);
        }
    }
    
    public function 
user_put() {
        
$id $this->put('id');
        
        
// Get the post data
        
$first_name strip_tags($this->put('first_name'));
        
$last_name strip_tags($this->put('last_name'));
        
$email strip_tags($this->put('email'));
        
$password $this->put('password');
        
$phone strip_tags($this->put('phone'));
        
        
// Validate the post data
        
if(!empty($id) && (!empty($first_name) || !empty($last_name) || !empty($email) || !empty($password) || !empty($phone))){
            
// Update user's account data
            
$userData = array();
            if(!empty(
$first_name)){
                
$userData['first_name'] = $first_name;
            }
            if(!empty(
$last_name)){
                
$userData['last_name'] = $last_name;
            }
            if(!empty(
$email)){
                
$userData['email'] = $email;
            }
            if(!empty(
$password)){
                
$userData['password'] = md5($password);
            }
            if(!empty(
$phone)){
                
$userData['phone'] = $phone;
            }
            
$update $this->user->update($userData$id);
            
            
// Check if the user data is updated
            
if($update){
                
// Set the response and exit
                
$this->response([
                    
'status' => TRUE,
                    
'message' => 'The user info has been updated successfully.'
                
], REST_Controller::HTTP_OK);
            }else{
                
// Set the response and exit
                
$this->response("Some problems occurred, please try again."REST_Controller::HTTP_BAD_REQUEST);
            }
        }else{
            
// Set the response and exit
            
$this->response("Provide at least one user info to update."REST_Controller::HTTP_BAD_REQUEST);
        }
    }

}

Config

routes.php
Specify the routes for REST API requests (login, registration, view, and update).

$route['api/authentication/login'] = 'api/authentication/login';
$route['api/authentication/registration'] = 'api/authentication/registration';
$route['api/authentication/user/(:num)(\.)([a-zA-Z0-9_-]+)(.*)'] = 'api/authentication/user/id/$1/format/$3$4';

Login and Registration with CodeIgniter RESTful Web Services

You can interact and use the CodeIgniter REST API methods to integrate the user login system in the different applications. The cURL allows you to make HTTP requests in PHP. We will use PHP cURL to interact with CodeIgniter REST API, and perform the GET, POST, and PUT requests. The following examples uses HTTP Basic authentication with API key to connect to the RESTful API.

User Registration via REST API:
The following code performs a POST request to insert the user data for registration (signup) via CodeIgniter REST API.

// API key
$apiKey 'CODEX@123';

// API auth credentials
$apiUser "admin";
$apiPass "1234";

// API URL
$url 'http://example.com/codeigniter/api/authentication/registration/';

// User account info
$userData = array(
    
'first_name' => 'John',
    
'last_name' => 'Doe',
    
'email' => 'john@example.com',
    
'password' => 'login_pass',
    
'phone' => '123-456-7890'
);

// Create a new cURL resource
$ch curl_init($url);

curl_setopt($chCURLOPT_TIMEOUT30);
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_ANY);
curl_setopt($chCURLOPT_HTTPHEADER, array("X-API-KEY: " $apiKey));
curl_setopt($chCURLOPT_USERPWD"$apiUser:$apiPass");
curl_setopt($chCURLOPT_POST1);
curl_setopt($chCURLOPT_POSTFIELDS$userData);

$result curl_exec($ch);

// Close cURL resource
curl_close($ch);

User Login via REST API:
The following code performs a POST request to validate the credential for login (sign in) via CodeIgniter REST API.

// API key
$apiKey 'CODEX@123';

// API auth credentials
$apiUser "admin";
$apiPass "1234";

// API URL
$url 'http://example.com/codeigniter/api/authentication/login/';

// User account login info
$userData = array(
    
'email' => 'john@example.com',
    
'password' => 'login_pass'
);

// Create a new cURL resource
$ch curl_init($url);

curl_setopt($chCURLOPT_TIMEOUT30);
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_ANY);
curl_setopt($chCURLOPT_HTTPHEADER, array("X-API-KEY: " $apiKey));
curl_setopt($chCURLOPT_USERPWD"$apiUser:$apiPass");
curl_setopt($chCURLOPT_POST1);
curl_setopt($chCURLOPT_POSTFIELDS$userData);

$result curl_exec($ch);

// Close cURL resource
curl_close($ch);

Retrieve User Account Data via REST API:
The following code performs a GET request to retrieve the user’s account data via CodeIgniter REST API.

// API key
$apiKey 'CODEX@123';

// API auth credentials
$apiUser "admin";
$apiPass "1234";

// Specify the ID of the user
$userID 1

// API URL
$url 'http://example.com/codeigniter/api/authentication/user/'.$userID;

// Create a new cURL resource
$ch curl_init($url);

curl_setopt($chCURLOPT_TIMEOUT30);
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_ANY);
curl_setopt($chCURLOPT_HTTPHEADER, array("X-API-KEY: " $apiKey));
curl_setopt($chCURLOPT_USERPWD"$apiUser:$apiPass");

$result curl_exec($ch);

// Close cURL resource
curl_close($ch);

Update User Account via REST API:
The following code performs a PUT request to update the user data via CodeIgniter REST API.

// API key
$apiKey 'CODEX@123';

// API auth credentials
$apiUser "admin";
$apiPass "1234";

// Specify the ID of the user
$userID 1

// API URL
$url 'http://example.com/codeigniter/api/authentication/user/';

// User account info
$userData = array(
    
'id' => 1,
    
'first_name' => 'John2',
    
'last_name' => 'Doe2',
    
'email' => 'john2@example.com',
    
'password' => 'user_new_pass',
    
'phone' => '545-856-3439'
);

// Create a new cURL resource
$ch curl_init($url);

curl_setopt($chCURLOPT_TIMEOUT30);
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
curl_setopt($chCURLOPT_HTTPAUTHCURLAUTH_ANY);
curl_setopt($chCURLOPT_HTTPHEADER, array('X-API-KEY: '.$apiKey'Content-Type: application/x-www-form-urlencoded'));
curl_setopt($chCURLOPT_USERPWD"$apiUser:$apiPass");
curl_setopt($chCURLOPT_CUSTOMREQUEST"PUT");
curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($userData));

$result curl_exec($ch);

// Close cURL resource
curl_close($ch);

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

9 Comments

  1. Nirdosh Kumar Said...
  2. RKV Said...
  3. Audrey Said...
  4. Noval H Said...
  5. Hassan Abubakar Manengelo Said...
  6. Tebogo Said...
  7. Gegli Said...
  8. Ahmed Haroon Said...
  9. کتاب های تجارت Said...

Leave a reply

keyboard_double_arrow_up