Curl batch request operation implemented in PHP

不言
Release: 2023-03-29 22:50:01
Original
3074 people have browsed it

This article mainly introduces the curl batch request operation implemented by PHP, and analyzes the specific batch creation of curl handles, batch execution handles, anti-jamming and other related operation skills of PHP using curl for batch request processing in the form of examples, which are needed Friends can refer to

This article describes the curl batch request operation implemented by PHP. Share it with everyone for your reference, the details are as follows:

<?php
$ch = array();
$res = array();
$conn = array();
$urls = array(
  &#39;baidu&#39; => "http://www.baidu.com/",
  &#39;cheyun&#39; => "http://auto.jrj.com.cn/",
  &#39;w3c&#39; => "http://www.w3cschool.cc/",
);
// 创建批处理cURL句柄
$mh = curl_multi_init();
foreach ($urls as $i => $url) {
  // 创建一对cURL资源
  $conn[$i] = curl_init();
  // 设置URL和相应的选项
  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跳转
  curl_setopt($conn[$i], CURLOPT_FOLLOWLOCATION, 1);
  // 增加句柄
  curl_multi_add_handle($mh, $conn[$i]);
}
$active = null;
//防卡死写法:执行批处理句柄
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) {
  //获取当前解析的cURL的相关传输信息
  $info = curl_multi_info_read($mh);
  //获取请求头信息
  $heards = curl_getinfo($conn[$i]);
  var_dump($heards);
  //获取输出的文本流
  $res[$i] = curl_multi_getcontent($conn[$i]);
  // 移除curl批处理句柄资源中的某个句柄资源
  curl_multi_remove_handle($mh, $conn[$i]);
  //关闭cURL会话
  curl_close($conn[$i]);
}
//关闭全部句柄
curl_multi_close($mh);
//var_dump($res);
Copy after login

##Related recommendations:

implemented by php xml operation class, php implements xml

php curl implements http and https request examples

The above is the detailed content of Curl batch request operation implemented in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!