侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

php curl批处理实现可控并发异步操作示例

php  /  管理员 发布于 4年前   187

本文实例讲述了php curl批处理实现可控并发异步操作。分享给大家供大家参考,具体如下:

通常情况下 PHP 中的 cURL 是阻塞运行的,就是说创建一个 cURL 请求以后必须等它执行成功或者超时才会执行下一个请求:API接口访问一般会首选CURL

在实际项目或者自己编写小工具(比如新闻聚合,商品价格监控,比价)的过程中, 通常需要从第3方网站或者API接口获取数据, 在需要处理1个URL队列时, 为了提高性能, 可以采用cURL提供的curl_multi_*族函数实现简单的并发.

'; print_r($response); echo '
' . date("Y-m-d H:i:s") . '   
'; echo '
' . str_repeat("-", 100) . '
';}$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', //秦美人 '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', //神曲 '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', //凡人修真 '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', //神魔仙界 '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', //倾世情缘 '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();

使用下来效果很好,没有副作用,并发数可控,应用之处多多,自己发挥想象吧

 * @link http://t.qq.com/JustPzy *//** *单一的请求对象 */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 ); }}/** * 包含请求列队处理 */class Curl { /**  * 请求url个数  * @var int  */ private $size    = 5; /**  * 等待所有cURL批处理中的活动连接等待响应时间  * @var int  */ private $timeout   = 5; /**  * 完成请求回调函数  * @var string  */ private $callback   = null; /**  * cRUL配置  * @var array  */ private $options   = array (CURLOPT_SSL_VERIFYPEER => 0,CURLOPT_RETURNTRANSFER => 1,CURLOPT_CONNECTTIMEOUT => 30 ); /**  * 请求头  * @var array  */ private $headers   = array (); /**  * 请求列队  * @var array  */ private $requests   = array (); /**  * 请求列队索引  * @var array  */ private $request_map  = array (); /**  * 错误  * @var array  */ private $errors   = array (); /**  * @access public  * @param string $callback 回调函数  * 该函数有4个参数($response,$info,$error,$request)  * $response url返回的body  * $info  cURL连接资源句柄的信息  * $error  错误  * $request  请求对象  */ public function __construct($callback = null) {  $this->callback = $callback; } /**  * 添加一个请求对象到列队  * @access public  * @param object $request  * @return boolean  */ public function add($request) {  $this->requests [] = $request;  return TRUE; } /**  * 创建一个请求对象并添加到列队  * @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; } /**  * 创建GET请求对象  * @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 ); } /**  * 创建一个POST请求对象  * @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 ); } /**  * 执行cURL  * @access public  * @param int $size 最大连接数  * @return Ambigous |boolean  */ public function execute($size = null) {  if (sizeof ( $this->requests ) == 1) {   return $this->single_curl ();  } else {   return $this->rolling_curl ( $size );  } } /**  * 单个url请求  * @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; } /**  * 多个url请求  * @access private  * @param int $size 最大连接数  * @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 ();  //添加cURL连接资源句柄到map索引  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;   //有一个请求完成则回调   while ( $done = curl_multi_info_read ( $master ) ) {    //$done 完成的请求句柄    $info = curl_getinfo ( $done ['handle'] );//    $output = curl_multi_getcontent ( $done ['handle'] );//    $error = curl_error ( $done ['handle'] );//    $this->set_error ( $error );    //调用回调函数,如果存在的话    $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'] );    //从列队中移除已经完成的request    curl_multi_remove_handle ( $master, $done ['handle'] );   }   //等待所有cURL批处理中的活动连接   if ($active)    curl_multi_select ( $master, $this->timeout );  } while ( $active );  //完成关闭  curl_multi_close ( $master );  return true; } /**  * 获取没得请求对象的cURL配置  * @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; } /**  * 设置错误信息  * @access public  * @param string $msg  */ public function set_error($msg) {  if (! empty ( $msg ))   $this->errors [] = $msg; } /**  * 获取错误信息  * @access public  * @param string $open  * @param string $close  * @return string  */ public function display_errors($open = '

', $close = '

') { $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 */

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php curl用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《PHP运算与运算符用法总结》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

您可能感兴趣的文章:

  • PHP使用CURL_MULTI实现多线程采集的例子
  • PHP Curl多线程原理实例详解
  • PHP使用CURL实现多线程抓取网页
  • php结合curl实现多线程抓取
  • php中foreach结合curl实现多线程的方法分析
  • php使用curl_init()和curl_multi_init()多线程的速度比较详解
  • PHP CURL 多线程操作代码实例
  • 浅谈php使用curl模拟多线程发送请求
  • PHP curl批处理及多请求并发实现方法分析
  • PHP中使用CURL发送get/post请求上传图片批处理功能
  • php使用curl模拟多线程实现批处理功能示例


  • 上一条:
    phpmyadmin提示The mbstring extension is missing的解决方法
    下一条:
    PHP GD库生成图像的几个函数总结
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客