php curl batch implementation controllable concurrent asynchronous operation example

  • 2021-10-11 17:47:00
  • OfStack

In this paper, an example is given to describe the controllable concurrent asynchronous operation of php curl batch processing. Share it for your reference, as follows:

Usually, cURL in PHP is blocked, that is to say, after creating an cURL request, it must wait for it to execute successfully or time out before executing the next request: API interface access 1 generally prefers CURL

In the process of actual project or compiling gadgets (such as news aggregation, commodity price monitoring and price comparison), it is usually necessary to obtain data from the third-party website or API interface. When one URL queue needs to be processed, in order to improve performance, it can be provided by cURL curl_multi_* Family functions to achieve simple concurrency.


<?php
include 'curl.class.php';
function callback($response, $info, $error, $request)
{
 echo 'response:<br>';
 print_r($response);
 echo '<br>' . date("Y-m-d H:i:s") . '&nbsp;&nbsp;&nbsp;<br>';
 echo '<br>' . str_repeat("-", 100) . '<br>';
}
$USER_COOKIE = (!empty($_REQUEST['cookie'])) ? $_REQUEST['cookie'] : file_get_contents("cookie.txt");
$curl = new Curl ("callback");
$data = array(
 array(
  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=qmr&type=rec_gametime&referfrom=&rt=0.42521539455332336', // Qin Beauty 
  'method' => 'POST',
  'post_data' => '',
  'header' => null,
  'options' => array(
   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=qmr&fenQuNum=3",
   CURLOPT_COOKIE => $USER_COOKIE,
  )
 ),
 array(
  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=sq&type=rec_gametime&referfrom=&rt=0.42521539455332336', // Divine Comedy 
  'method' => 'POST',
  'post_data' => '',
  'header' => null,
  'options' => array(
   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=sq&fenQuNum=41",
   CURLOPT_COOKIE => $USER_COOKIE,
  )
 ),
 array(
  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=frxz&type=rec_gametime&referfrom=&rt=0.42521539455332336', // Ordinary people practice truth 
  'method' => 'POST',
  'post_data' => '',
  'header' => null,
  'options' => array(
   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=frxz&fenQuNum=3",
   CURLOPT_COOKIE => $USER_COOKIE,
  )
 ),
 array(
  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=smxj&type=rec_gametime&referfrom=&rt=0.42521539455332336', // Gods and demons celestial realm 
  'method' => 'POST',
  'post_data' => '',
  'header' => null,
  'options' => array(
   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=smxj&fenQuNum=2",
   CURLOPT_COOKIE => $USER_COOKIE,
  )
 ),
 array(
  'url' => 'http://dyactive2.vip.xunlei.com/com_sign/?game=qsqy&type=rec_gametime&referfrom=&rt=0.42521539455332336', // Love for the world 
  'method' => 'POST',
  'post_data' => '',
  'header' => null,
  'options' => array(
   CURLOPT_REFERER => "http://niu.xunlei.com/entergame/?gameNo=qsqy&fenQuNum=11",
   CURLOPT_COOKIE => $USER_COOKIE,
  )
 ),
);
foreach ($data as $val) {
 $request = new Curl_request ($val ['url'], $val ['method'], $val ['post_data'], $val ['header'], $val ['options']);
 $curl->add($request);
}
$curl->execute();
echo $curl->display_errors();

Use down the effect is very good, no side effects, concurrent number can be controlled, the application of many, their own imagination


<?php
/**
 * cURL Batch processing   Tool class 
 * 
 * @since Version 1.0
 * @author Justmepzy <justmepzy@gmail.com>
 * @link http://t.qq.com/JustPzy
 */
/**
 * Single 1 Request object of 
 */
class Curl_request {
 public $url   = '';
 public $method   = 'GET';
 public $post_data  = null;
 public $headers  = null;
 public $options  = null;
 /**
  * 
  * @param string $url
  * @param string $method
  * @param string $post_data
  * @param string $headers
  * @param array $options
  * @return void
  */
 public function __construct($url, $method = 'GET', $post_data = null, $headers = null, $options = null) {
  $this->url = $url;
  $this->method = strtoupper( $method );
  $this->post_data = $post_data;
  $this->headers = $headers;
  $this->options = $options;
 }
 /**
  * @return void
  */
 public function __destruct() {
  unset ( $this->url, $this->method, $this->post_data, $this->headers, $this->options );
 }
}
/**
 *  Include request queuing processing 
 */
class Curl {
 /**
  *  Request url Number 
  * @var int
  */
 private $size    = 5;
 /**
  *  Waiting for all cURL Active Connection Waiting Response Time in Batch 
  * @var int
  */
 private $timeout   = 5;
 /**
  *  Complete the request callback function 
  * @var string
  */
 private $callback   = null;
 /**
  * cRUL Configure 
  * @var array
  */
 private $options   = array (CURLOPT_SSL_VERIFYPEER => 0,CURLOPT_RETURNTRANSFER => 1,CURLOPT_CONNECTTIMEOUT => 30 );
 /**
  *  Request header 
  * @var array
  */
 private $headers   = array ();
 /**
  *  Request to line up 
  * @var array
  */
 private $requests   = array ();
 /**
  *  Request queue index 
  * @var array
  */
 private $request_map  = array ();
 /**
  *  Errors 
  * @var array
  */
 private $errors   = array ();
 /**
  * @access public
  * @param string $callback  Callback function 
  *  The function has 4 Parameters ($response,$info,$error,$request)
  * $response url Returned body
  * $info  cURL Connect resource handle information 
  * $error   Errors 
  * $request   Request object 
  */
 public function __construct($callback = null) {
  $this->callback = $callback;
 }
 /**
  *  Add 1 Request objects to queue 
  * @access public
  * @param object $request
  * @return boolean
  */
 public function add($request) {
  $this->requests [] = $request;
  return TRUE;
 }
 /**
  *  Create 1 Request objects and add them to the queue 
  * @access public
  * @param string $url
  * @param string $method
  * @param string $post_data
  * @param string $headers
  * @param array $options
  * @return boolean
  */
 public function request($url, $method = 'GET', $post_data = null, $headers = null, $options = null) {
  $this->requests [] = new Curl_request ( $url, $method, $post_data, $headers, $options );
  return TRUE;
 }
 /**
  *  Create GET Request object 
  * @access public
  * @param string $url
  * @param string $headers
  * @param array $options
  * @return boolean
  */
 public function get($url, $headers = null, $options = null) {
  return $this->request ( $url, "GET", null, $headers, $options );
 }
 /**
  *  Create 1 A POST Request object 
  * @access public
  * @param string $url
  * @param string $post_data
  * @param string $headers
  * @param array $options
  * @return boolean
  */
 public function post($url, $post_data = null, $headers = null, $options = null) {
  return $this->request ( $url, "POST", $post_data, $headers, $options );
 }
 /**
  *  Execute cURL
  * @access public
  * @param int $size  Maximum number of connections 
  * @return Ambigous <boolean, mixed>|boolean
  */
 public function execute($size = null) {
  if (sizeof ( $this->requests ) == 1) {
   return $this->single_curl ();
  } else {
   return $this->rolling_curl ( $size );
  }
 }
 /**
  *  Single url Request 
  * @access private
  * @return mixed|boolean
  */
 private function single_curl() {
  $ch = curl_init ();
  $request = array_shift ( $this->requests );
  $options = $this->get_options ( $request );
  curl_setopt_array ( $ch, $options );
  $output = curl_exec ( $ch );
  $info = curl_getinfo ( $ch );
  // it's not neccesary to set a callback for one-off requests
  if ($this->callback) {
   $callback = $this->callback;
   if (is_callable ( $this->callback )) {
    call_user_func ( $callback, $output, $info, $request );
   }
  } else
   return $output;
  return true;
 }
 /**
  *  Multiple url Request 
  * @access private
  * @param int $size  Maximum number of connections 
  * @return boolean
  */
 private function rolling_curl($size = null) {
  if ($size)
   $this->size = $size;
  else 
   $this->size = count($this->requests);
  if (sizeof ( $this->requests ) < $this->size)
   $this->size = sizeof ( $this->requests );
  if ($this->size < 2)
   $this->set_error ( 'size must be greater than 1' );
  $master = curl_multi_init ();
  // Add cURL Connect resource handles to map Index 
  for($i = 0; $i < $this->size; $i ++) {
   $ch = curl_init ();
   $options = $this->get_options ( $this->requests [$i] );
   curl_setopt_array ( $ch, $options );
   curl_multi_add_handle ( $master, $ch );
   $key = ( string ) $ch;
   $this->request_map [$key] = $i;
  }
  $active = $done = null;
  do {
   while ( ($execrun = curl_multi_exec ( $master, $active )) == CURLM_CALL_MULTI_PERFORM )
    ;
   if ($execrun != CURLM_OK)
    break;
   // Have 1 Callback when the request is completed 
   while ( $done = curl_multi_info_read ( $master ) ) {
    //$done  Completed request handle 
    $info = curl_getinfo ( $done ['handle'] );//
    $output = curl_multi_getcontent ( $done ['handle'] );//
    $error = curl_error ( $done ['handle'] );//
    $this->set_error ( $error );
    // Call callback function , If it exists, 
    $callback = $this->callback;
    if (is_callable ( $callback )) {
     $key = ( string ) $done ['handle'];
     $request = $this->requests [$this->request_map [$key]];
     unset ( $this->request_map [$key] );
     call_user_func ( $callback, $output, $info, $error, $request );
    }
    curl_close ( $done ['handle'] );
    // Removes the completed request
    curl_multi_remove_handle ( $master, $done ['handle'] );
   }
   // Waiting for all cURL Active connections in a batch 
   if ($active)
    curl_multi_select ( $master, $this->timeout );
  } while ( $active );
  // Complete shutdown 
  curl_multi_close ( $master );
  return true;
 }
 /**
  *  Object that does not have a request object cURL Configure 
  * @access private
  * @param object $request
  * @return array
  */
 private function get_options($request) {
  $options = $this->__get ( 'options' );
  if (ini_get ( 'safe_mode' ) == 'Off' || ! ini_get ( 'safe_mode' )) {
   $options [CURLOPT_FOLLOWLOCATION] = 1;
   $options [CURLOPT_MAXREDIRS] = 5;
  }
  $headers = $this->__get ( 'headers' );
  if ($request->options) {
   $options = $request->options + $options;
  }
  $options [CURLOPT_URL] = $request->url;
  if ($request->post_data && strtolower($request->method) == 'post' ) {
   $options [CURLOPT_POST] = 1;
   $options [CURLOPT_POSTFIELDS] = $request->post_data;
  }
  if ($headers) {
   $options [CURLOPT_HEADER] = 0;
   $options [CURLOPT_HTTPHEADER] = $headers;
  }
  return $options;
 }
 /**
  *  Set error message 
  * @access public
  * @param string $msg
  */
 public function set_error($msg) {
  if (! empty ( $msg ))
   $this->errors [] = $msg;
 }
 /**
  *  Get error information 
  * @access public
  * @param string $open
  * @param string $close
  * @return string
  */
 public function display_errors($open = '<p>', $close = '</p>') {
  $str = '';
  foreach ( $this->errors as $val ) {
   $str .= $open . $val . $close;
  }
  return $str;
 }
 /**
  * @access public
  * @param string $name
  * @param string $value
  * @return boolean
  */
 public function __set($name, $value) {
  if ($name == 'options' || $name == 'headers') {
   $this->{$name} = $value + $this->{$name};
  } else {
   $this->{$name} = $value;
  }
  return TRUE;
 }
 /**
  * 
  * @param string $name
  * @return mixed
  * @access public
  */
 public function __get($name) {
  return (isset ( $this->{$name} )) ? $this->{$name} : null;
 }
 /**
  * @return void
  * @access public
  */
 public function __destruct() {
  unset ( $this->size, $this->timeout, $this->callback, $this->options, $this->headers, $this->requests, $this->request_map, $this->errors );
 }
}
// END Curl Class
/* End of file curl.class.php */

For more readers interested in PHP related contents, please check the special topics of this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "PHP Operation and Operator Usage Summary" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: