loading

How to User Login and Registration with CodeIgniter REST API

How to User Login and Registration with CodeIgniter REST API

How to User Login and Registration with CodeIgniter REST API

0 Sales

Free

RESTful web services make it easy to share data across various applications. RESTful web services must be established if your online application has to communicate across platforms. Using RESTful API, the application may connect to and interact with many platforms (web, mobile, etc.). For data management across platforms, the REST API employs HTTP requests such as GET, PUT, POST, and DELETE.

The CodeIgniter RESTful web service is the simplest method to include a REST API service into a web application. You can quickly construct a REST API in CodeIgniter by using CodeIgniter Rest Server. In this article, we will teach you how to leverage the CodeIgniter REST API to implement user login and registration.

To develop a REST API with CodeIgniter, follow the instructions below.

 - Configure the Rest Server in CodeIgniter.
 - Create an API function to handle user login using a POST request.
 - Create an API function to handle user registration with a POST request.
 - Create an API method for retrieving user account data via a GET request.
 - Create an API function to update user information with a PUT request.
 - Use the CodeIgniter RESTful API to interact.

Create Database Tables

A table in the database must be built to contain user account information. In the MySQL database, the below SQL generates a users table with some basic columns.

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 are examples: SQL generates a keys table in order to hold the REST API key for verification.

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;

In the keys table, import the API key data that will be used to confirm the API call.

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

CodeIgniter REST Controller Setup

To create RESTful web services in CodeIgniter, we will utilise the REST Controller framework. To incorporate a RESTful server into CodeIgniter, use the REST Controller package.

1. Place the REST configuration file (rest.php) in the application/config/ subdirectory and configure the API.
     - Activate REST API authentication.

$config['rest_auth'] = 'basic';

     - Set the API login username and password.

$config['rest_valid_logins'] = ['admin' => '1234'];

     - Set the name of the table that contains the API key.

$config['rest_keys_table'] = 'keys';

     - Activate the REST API key.

$config['rest_enable_keys'] = TRUE;

2. In the application/libraries/ folder, insert the CodeIgniter Rest Controller library (REST Controller.php).

3. Put the CodeIgniter Format library (Format.php) in the application/libraries/ directory.
4. For multilingual support, place the Rest Controller's language (rest controller lang.php) in the application/language/english/ folder.

Model (User.php)

The database-related operations are handled by the User model (fetch, insert, update, and delete).

  - __construct()

      - Load the database library into memory.
      - Enter the name of the table to be utilised.
 - getRows() – Fetch data from the database depending on the specified criterion and return it as an array.
 - insert() – Insert the information into the database.
 - update() – Update the data in the database depending on the ID.
 - delete() – Delete data from the database depending on the ID.

<?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 a good idea to keep API-related controllers in their own folder. Under this example, the API controller will be placed in the controllers/api/ subdirectory.
The API requests are handled by the Authentication API controller. It enables the implementation of a RESTful interface for user login and registration using GET, POST, and PUT requests.

 - __construct() – Upload the User model in order to interact with the database.

 - login_post()

      - Obtain the login information from the POST request.
      - By using getRows() function of the User model, verify the login against the database.
      - Configure the answer and quit.

  - registration_post()

      - The enrollment data may be obtained through the POST request.
      - Use the insert() function of the User model to verify and add user data into the database.

 - user_get()

      - Using the getRows() function of the User model, retrieve user data from the database.
      - If the ID is given, it delivers a single user's data; otherwise, it gives all users' data.
      - Configure the answer and quit.

  - user_put()

      - Both user ID and info from the PUT request are returned.
      - Based on the ID, update the user info in the database.

<?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

Set the paths for REST API queries (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

To link the user login process in multiple apps, you may communicate with and use the CodeIgniter REST API functions. In PHP, you may use cURL to make HTTP requests. To communicate with the CodeIgniter REST API and make the GET, POST, and PUT queries, we will utilise PHP cURL. To connect to the RESTful API, the following examples employ HTTP Basic authentication and an API key.

User Registration via REST API:
The code sends a Request message to the CodeIgniter REST API to input user data for registration (signup).

// API key
$apiKey '[email protected]';

// 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' => '[email protected]',
    '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 code sends a POST request to the CodeIgniter REST API to authenticate the information for login (sign in).

// API key
$apiKey '[email protected]';

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

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

// User account login info
$userData = array(
    'email' => '[email protected]',
    '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 makes a GET call to the CodeIgniter REST API to obtain the user's account info.

// API key
$apiKey '[email protected]';

// 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 sends a PUT request to the CodeIgniter REST API to update the user info.

// 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' => '[email protected]',
    '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);

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Feb 16, 2022

Updated Date : Feb 16, 2022

Ratings

Comments : 0

Downloads : 0