http://blog.qita.in/?post=496
- /**
- * HTTP request processing class (encapsulated based on Curl)
- *
- * @author Xiwei Ye
- * @version $Id $
- */
- Class Cls_http_request
- {
- /**
- * Get mode request (Curl)
- *
- * @param string $url the requested URL
- * @param integer $timeout time-out (s)
- * @return String (Request succeeded) | False (Request failed)
- */
- public static function Curl_get ($url, $timeout = 1)
- {
- $ch = Curl_init ();
- curl_setopt ($ch, Curlopt_url, $url);
- curl_setopt ($ch, Curlopt_returntransfer, 1);
- curl_setopt ($ch, Curlopt_timeout, $timeout);
- $result = curl_exec ($ch);
- Curl_close ($ch);
- if (is_string ($result) && strlen ($result))
- {
- return $result;
- }
- Else
- {
- return false;
- }
- }
- /**
- * Post Mode request
- *
- * @param string $url the requested URL
- * @param array of parameters for array $data request (associative array)
- * @param integer $timeout time-out (s)
- * @return String (Request succeeded) | False (Request failed)
- */
- public static function Curl_post ($url, $data, $timeout = 2)
- {
- $ch = Curl_init ();
- curl_setopt ($ch, Curlopt_url, $url);
- curl_setopt ($ch, Curlopt_returntransfer, 1);
- curl_setopt ($ch, Curlopt_post, 1);
- curl_setopt ($ch, Curlopt_postfields, $data);
- curl_setopt ($ch, curlopt_http_version, CURL_HTTP_VERSION_1_0);
- curl_setopt ($ch, Curlopt_timeout, $timeout);
- $result = curl_exec ($ch);
- Curl_close ($ch);
- if (is_string ($result) && strlen ($result))
- {
- return $result;
- }
- Else
- {
- return false;
- }
- }
- /**
- * Multiple URL parallel requests
- *
- * @param array $urls URL
- * @param integer $timeout time-out (s)
- * @return Array $res return results
- */
- public static function Curl_get_urls ($urls, $timeout = 1)
- {
- $MH =curl_multi_init ();
- $chs =array ();
- foreach ($urls as $url)
- {
- $ch =curl_init ();
- curl_setopt ($ch, Curlopt_url, $url);
- curl_setopt ($ch, Curlopt_header,false);
- curl_setopt ($ch, curlopt_returntransfer,true);
- curl_setopt ($ch, curlopt_connecttimeout,1);
- curl_setopt ($ch, Curlopt_timeout, $timeout);
- Curl_multi_add_handle ($MH, $ch);
- $chs []= $ch;
- }
- $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);
- }
- }
- $res =array ();
- foreach ($chs as $ch)
- {
- $res []=curl_multi_getcontent ($ch);
- Curl_multi_remove_handle ($MH, $ch);
- }
- Curl_multi_close ($MH);
- return $res;
- }
- }
Copy Code |