欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP CURL 多线程 GET/POST 类

程序员文章站 2022-06-01 21:25:20
...
  1. /****************************************************************
  2. PHP CURL 多线程 GET/POST
  3. curl(array('url?get=data','url'),array('','post_data'));
  4. *****************************************************************/
  5. function curl($urls,$post) {
  6. $queue = curl_multi_init();
  7. $map = array();
  8. foreach ($urls as $key => $url) {
  9. $ch = curl_init();
  10. curl_setopt($ch, CURLOPT_URL, $url);
  11. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  12. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  13. curl_setopt($ch, CURLOPT_POSTFIELDS, $post[$key]);
  14. curl_setopt($ch, CURLOPT_HEADER, 0);
  15. curl_setopt($ch, CURLOPT_NOSIGNAL, true);
  16. curl_multi_add_handle($queue, $ch);
  17. $map[(string) $ch] = $url;
  18. }
  19. $responses = array();
  20. do {
  21. while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM) ;
  22. if ($code != CURLM_OK) { break; }
  23. while ($done = curl_multi_info_read($queue)) {
  24. $error = curl_error($done['handle']);
  25. $results = curl_multi_getcontent($done['handle']);
  26. $responses[$map[(string) $done['handle']]] = compact('error', 'results');
  27. curl_multi_remove_handle($queue, $done['handle']);
  28. curl_close($done['handle']);
  29. }
  30. if ($active > 0) {
  31. curl_multi_select($queue, 0.5);
  32. }
  33. } while ($active);
  34. curl_multi_close($queue);
  35. return $responses;
  36. }
复制代码

多线程, PHP, CURL