http请求处理类-LMLPHP http://blog.qita.in/?post=496
  1. /**
  2. * http请求处理类(基于CURL进行封装)
  3. *
  4. * @author Xiwei Ye
  5. * @version $Id$
  6. */
  7. class cls_http_request
  8. {
  9. /**
  10. * get方式请求(curl)
  11. *
  12. * @param string $url 请求的url
  13. * @param integer $timeout 超时时间(s)
  14. * @return string(请求成功) | false(请求失败)
  15. */
  16. public static function curl_get($url, $timeout = 1)
  17. {
  18. $ch = curl_init();
  19. curl_setopt($ch, CURLOPT_URL, $url);
  20. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  21. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  22. $result = curl_exec($ch);
  23. curl_close($ch);
  24. if (is_string($result) && strlen($result))
  25. {
  26. return $result;
  27. }
  28. else
  29. {
  30. return false;
  31. }
  32. }
  33. /**
  34. * post方式请求
  35. *
  36. * @param string $url 请求的url
  37. * @param array $data 请求的参数数组(关联数组)
  38. * @param integer $timeout 超时时间(s)
  39. * @return string(请求成功) | false(请求失败)
  40. */
  41. public static function curl_post($url, $data, $timeout = 2)
  42. {
  43. $ch = curl_init();
  44. curl_setopt($ch, CURLOPT_URL, $url);
  45. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  46. curl_setopt($ch, CURLOPT_POST, 1);
  47. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  48. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  49. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  50. $result = curl_exec($ch);
  51. curl_close($ch);
  52. if (is_string($result) && strlen($result))
  53. {
  54. return $result;
  55. }
  56. else
  57. {
  58. return false;
  59. }
  60. }
  61. /**
  62. * 多个url并行请求
  63. *
  64. * @param array $urls url数组
  65. * @param integer $timeout 超时时间(s)
  66. * @return array $res 返回结果
  67. */
  68. public static function curl_get_urls($urls, $timeout = 1)
  69. {
  70. $mh=curl_multi_init();
  71. $chs=array();
  72. foreach($urls as $url)
  73. {
  74. $ch=curl_init();
  75. curl_setopt($ch,CURLOPT_URL,$url);
  76. curl_setopt($ch,CURLOPT_HEADER,false);
  77. curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  78. curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
  79. curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);
  80. curl_multi_add_handle($mh,$ch);
  81. $chs[]=$ch;
  82. }
  83. $active=null;
  84. do {
  85. $mrc=curl_multi_exec($mh,$active);
  86. }while($mrc == CURLM_CALL_MULTI_PERFORM);
  87. while($active && $mrc == CURLM_OK)
  88. {
  89. if(curl_multi_select($mh) != -1)
  90. {
  91. do{
  92. $mrc=curl_multi_exec($mh,$active);
  93. }while($mrc == CURLM_CALL_MULTI_PERFORM);
  94. }
  95. }
  96. $res=array();
  97. foreach($chs as $ch)
  98. {
  99. $res[]=curl_multi_getcontent($ch);
  100. curl_multi_remove_handle($mh,$ch);
  101. }
  102. curl_multi_close($mh);
  103. return $res;
  104. }
  105. }
复制代码


09-18 23:34