Asynchronous Process, Multi threading or Multitasking in Codeigniter PHP

This tutorial explains how to implement Asynchronous Process, Multi threading or Multitasking in Codeigniter PHP. It allows applications to complete multiple tasks in parallel.



Introduction

Asynchronous Process means that a process operates independently of other process. It executes process in background.

 

In this tutorial we will learn how to implement multiple processes that do not depend on each other’s and execute multiple task in background using PHP Languge.

In this tutorial, we will create a library in the /application/libraries directory. Within this library we will implement a method in which send a server post request and close this method. It performs independent of other task.

 

Create Library

Now, we will create a Mylibrary.php file in the /application/libraries/
directory. In this library, we will add a method in which get URL and Array as a parameter. We will pass array in the http_build_query() to build post string. We will also use fsockopen() to send post request to server. Here is the code of Mylibrary.php

<?php  

class Mylibrary
{

    public function __construct()
    {
        $this->ci =& get_instance();
    }

    function do_in_background($url, $params)
    {
	    $post_string = http_build_query($params);
	    $parts = parse_url($url);
            $errno = 0;
	    $errstr = "";

	   //Use SSL & port 443 for secure servers
	   //Use otherwise for localhost and non-secure servers
	   //For secure server
	    $fp = fsockopen('ssl://' . $parts['host'], isset($parts['port']) 
                   ? $parts['port'] : 443, $errno, $errstr, 30);
	    //For localhost and un-secure server
	   //$fp = fsockopen($parts['host'], isset($parts['port']) 
                    ? $parts['port'] : 80, $errno, $errstr, 30);
	    if(!$fp)
	    {
	        echo "Some thing Problem";    
	    }
	    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
	    $out.= "Host: ".$parts['host']."\r\n";
	    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
	    $out.= "Content-Length: ".strlen($post_string)."\r\n";
	    $out.= "Connection: Close\r\n\r\n";
	    if (isset($post_string)) $out.= $post_string;
	    fwrite($fp, $out);
	    fclose($fp);
  }
}
?>

 

Create method

We need to create multiple method to be call in parallel in the controller. In this example, we will create two method to send mail and insert data.

 

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

class Test extends CI_Controller {

        /**
         * load list modal and helpers
         */
         function __Construct(){
           parent::__Construct();
           $this->load->helper(array('form', 'url'));
           $this->load->model('test_model');
         }
    
        /**
         *  @desc : Function to send mail 
         *  @param :void
         *  @return : void
         */
	  public function sendmail(){
            $this->load->library('email');
	        $user_email  = $_POST['email'];
	        $message     = "Testing";
	     
	        $this->email->from('anand.abhay1910@gmail.com', 'Test');
	        $this->email->to($user_email); 
	        $this->email->subject("test");
	        $this->email->message($message);  
	        $this->email->send();
	    }

        /**
         *  @desc : Function to call insert() method 
         *  of test_model to insert post data in database
         *  @param :void
         *  @return : void
         */
	  public function insert(){
	           $email = $this->input->post('email');
               $name = $this->input->post('name');
               $this->test_model->insert($email, $name);
          }
}

 

Call Multiple Task

To execute multiple task or process in parallel or independent. First, we need to include library in the controller then call do_in_background() function of library with url and array data as a parameter.

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

class Test extends CI_Controller {

        /**
         * load list modal, library and helpers
         */
         function __Construct(){
           parent::__Construct();
           $this->load->helper(array('form', 'url'));
           $this->load->model('test_model');
           $this->load->library('mylibrary');
         }
         
        /**
         *  @desc : Function to perform multiple task in background
         *  @param :void
         *  @return : void
         */
         public  function index(){

               $url = base_url()."test/sendmail";
               $url1 = base_url()."test/insert";
         	
               $param = array('email' => "anand.abhay1910@gmail.com" );
               $param1 = array('name' => "Abhay",
                               'email' => "anand.abhay1910@gmail.com" );

               $this->mylibrary->do_in_background($url, $param);
               $this->mylibrary->do_in_background($urls, $param1);
            
	    }
        
        /**
         *  @desc : Function to send mail 
         *  @param :void
         *  @return : void
         */
	    public function sendmail(){

		    $this->load->library('email');
	        $user_email  = $_POST['email'];
	        $message     = "Testing";
	     
	        $this->email->from('heyrajcool@gmail.com', 'Around');
	        $this->email->to($user_email); 
	        $this->email->subject("test");
	        $this->email->message($message);  
	        $this->email->send();
	    }
        
         /**
         *  @desc : Function to call insert() method 
         *  of test_model to insert data in database
         *  @param :void
         *  @return : void
         */
	   public function insert(){

	       $email = $this->input->post('email');
           $name = $this->input->post('name');
           $this->test_model->insert($email, $name);
	  }
}

 


The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com
  • pani pozna pana

    Heya i’m for the first time here. I found this board
    and I find It really useful & it helped me out a lot.
    I hope to give something back and help others like you helped me.

  • Thanks

  • Sheena

    Fabulous, what a webpage it is! This blog provides
    helpfull information to us, keep it up.

  • Niranjan N Raju

    Hi Anand, happy to see a simple way to implement multi tasking. I followed the tutorial, but for me, do_in_background() is getting called, but its not executing the statements in that.. Any suggestions?? Should i change anything??

    • Hi Niranjan,
      Please check your port and ssl. First you execute asynchornous method in sync way then debug your code. After your code is correct then put in asynchronous

    • abhayanand1910

      Hi Niranjan,

      Please check your port and ssl. First you execute asynchornous method in sync way then debug your code. After your code is correct then put in asynchronous

      • Niranjan N Raju

        Hi, thank you for your reply. If I execute the functions directly, its
        working(In which I am inserting 1000 rows to database), but if i call
        same in asynchornous way, its not working.

        • abhayanand1910

          Can you explain, exactly what are you doing..

          • Niranjan N Raju

            Ya… I have 2 function in which I am trying to insert 1000 rows to database. If i call functions separately, its working and both the functions are inserting 1000 rows in a table. But if I call in asynchornous way, its not working.

          • abhayanand1910

            Please check response.. Use
            while (!feof($fp)) {
            echo fgets($fp, 128);
            }

            before fclose($fp); in library

            Also Check our fscokopen for your secure and non secure server.

          • Niranjan N Raju

            Thank you for your support. I was able to fix the issue i had. Great tutorial

          • abhayanand1910

            Glad, your issue was fixed..