PHP Multi threading with Multi Curl Quick Tips

Author: | Posted in PHP, Quick Tips No comments

PHP doesn’t have in-built support for multi threading. Some web applications need to perform several tasks that may take a while to finish. When there are many tasks to execute, it may take a long time to finish all of them if they are executed sequentially, i.e., one after another. A possible solution for this problem is to execute several tasks at the same time using separate processes or threads.

You can implement multi threading concept by below mentioned options:

  1. Pthread
  2. Multi Curl
  3. Create separate process through daemon

Multi Curl:

A more efficient implementation of curl_multi() curl_multi is a great way to process multiple HTTP requests in parallel in PHP.

curl_multi is particularly handy when working with large data sets (like fetching thousands of RSS feeds at one time).

 Example:

<?php
class multicurl {
private $multi;
private $curlArray;
public function __construct() {
$this->multi = curl_multi_init();
$this->curlArray = array();
}
public function addingHandler($id, $url, $req_xml) {
$this->curlArray[$id] = curl_init();
curl_setopt($this->curlArray[$id], CURLOPT_URL, $url);
curl_setopt($this->curlArray[$id], CURLOPT_HEADER, 0);
curl_setopt($this->curlArray[$id], CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curlArray[$id], CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->curlArray[$id], CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($this->curlArray[$id], CURLOPT_POST, true);
curl_setopt($this->curlArray[$id], CURLOPT_TIMEOUT, CURL_TIME_OUT);
curl_setopt($this->curlArray[$id], CURLOPT_POSTFIELDS, $req_xml);
curl_multi_add_handle($this->multi, $this->curlArray[$id]);
}
public function execute() {
$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($this->multi, $active);
} while ($active > 0);
}
public function getContent($id) {
$active = 1;
$mrc = CURLM_OK;
while ($active && $mrc == CURLM_OK) {
do {
usleep(200);
$mrc = curl_multi_exec($this->multi, $active);
} while ($active > 0);
}
$data = curl_multi_getcontent($this->curlArray[$id]);
curl_multi_remove_handle($this->multi, $this->curlArray[$id]);
return $data;
}
public function closeHandler() {
curl_multi_close($this->multi);
}
}

We need to create above class and follow steps as per below:

$obj = new multicurl();
$obj->addingHandler($id, $url, $req_xml)
$obj->execute();
$obj->getContent($id)
$obj->closeHandler()