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.

Don't Miss

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);
}
}

32 COMMENTS

  1. 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.

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

  3. any limit execution time this Asynchronous Process?
    because if I’m insert 100 records, it work,
    but if I try insert million record, only about 1000 records has success inserted

    • Are you sending million record in a single request or sending million request. If possible try to send million record in a single request.

  4. I am using CI 3.1 version now.
    I am going to send push notification in background for many device.
    But the library is not working now.
    What is the issue?

  5. Sir, I see here u’r hardcoding mail into $param but if I’m using a form then what should I write in $param ??

  6. Worked great. can get data and store into db.but

    how to get result/response in async method. i didn’t get any.
    $async1 = $this->asynclibrary->do_in_background($url, $param);

    print_r($async1); display nothing…

  7. hi, nice code thanks very helpful., but i want to sync automatically in background within 5 mint, how to do this. have you any reference code please send me.

  8. hi, property setup everything but when i send the request got this:


    HTTP/1.1 400 Bad Request
    Your browser sent a request that this server could not understand.

    the request send by the async:


    POST /codeigniter/index.php/Test/insert HTTP/1.1
    Host: 127.0.0.1
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 38
    Connection: Close

    name=ver.txt&content=something+in

  9. It’ѕ very trouble-free to find oսt аny topic on net
    as compared tto textbooks, ɑs I foսnd this post at thіs web site.

Leave a Reply to Noor Cancel reply

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com