Example of curl batch request operation implemented by PHP

  • 2021-10-15 10:03:46
  • OfStack

In this paper, an example is given to describe the batch request operation of curl implemented by PHP. Share it for your reference, as follows:


<?php
$ch = array();
$res = array();
$conn = array();
$urls = array(
  'baidu' => "http://www.baidu.com/",
  'cheyun' => "http://auto.jrj.com.cn/",
  'w3c' => "http://www.w3cschool.cc/",
);
//  Create a batch cURL Handle 
$mh = curl_multi_init();
foreach ($urls as $i => $url) {
  //  Create 1 Right cURL Resources 
  $conn[$i] = curl_init();
  //  Settings URL And the corresponding options 
  curl_setopt($conn[$i], CURLOPT_URL, $url);
  curl_setopt($conn[$i], CURLOPT_HEADER, 0);
  curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($conn[$i], CURLOPT_TIMEOUT, 10);
  //302 Jump 
  curl_setopt($conn[$i], CURLOPT_FOLLOWLOCATION, 1);
  //  Add handle 
  curl_multi_add_handle($mh, $conn[$i]);
}
$active = null;
// Anti-jamming writing: Execute batch handle 
do {
  $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
  if (curl_multi_select($mh) != -1) {
    do {
      $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
  }
}
foreach ($urls as $i => $url) {
  // Gets the currently resolved cURL Related transmission information of 
  $info = curl_multi_info_read($mh);
  // Get request header information 
  $heards = curl_getinfo($conn[$i]);
  var_dump($heards);
  // Gets the output text stream 
  $res[$i] = curl_multi_getcontent($conn[$i]);
  //  Remove curl A handle resource in a batch handle resource 
  curl_multi_remove_handle($mh, $conn[$i]);
  // Shut down cURL Conversation 
  curl_close($conn[$i]);
}
// Close all handles 
curl_multi_close($mh);
//var_dump($res);

For more readers interested in PHP related content, please check the 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" and "PHP Operation and Operator Usage Summary"

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


Related articles: