PHP的http請求處理類
[PHP]代碼
/**
* http請求處理類(基于CURL進行封裝)
*
* @author Xiwei Ye <yexiwei@gmail.com>
* @version $Id$
*/
class cls_http_request
{
/**
* get方式請求(curl)
*
* @param string $url 請求的url
* @param integer $timeout 超時時間(s)
* @return string(請求成功) | false(請求失敗)
*/
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方式請求
*
* @param string $url 請求的url
* @param array $data 請求的參數數組(關聯數組)
* @param integer $timeout 超時時間(s)
* @return string(請求成功) | false(請求失敗)
*/
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;
}
}
/**
* 多個url并行請求
*
* @param array $urls url數組
* @param integer $timeout 超時時間(s)
* @return array $res 返回結果
*/
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;
}
} 本文由用戶 suxiang. 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!