php 处理 http 请求,PHP的http请求处理类
* @version $Id$
*/
class cls_http_request
{
/**
* get方式請(qǐng)求(curl)
*
* @param string $url 請(qǐng)求的url
* @param integer $timeout 超時(shí)時(shí)間(s)
* @return string(請(qǐng)求成功) | false(請(qǐng)求失敗)
*/
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方式請(qǐng)求
*
* @param string $url 請(qǐng)求的url
* @param array $data 請(qǐng)求的參數(shù)數(shù)組(關(guān)聯(lián)數(shù)組)
* @param integer $timeout 超時(shí)時(shí)間(s)
* @return string(請(qǐng)求成功) | false(請(qǐng)求失敗)
*/
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;
}
}
/**
* 多個(gè)url并行請(qǐng)求
*
* @param array $urls url數(shù)組
* @param integer $timeout 超時(shí)時(shí)間(s)
* @return array $res 返回結(jié)果
*/
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;
}
}
總結(jié)
以上是生活随笔為你收集整理的php 处理 http 请求,PHP的http请求处理类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无法隐藏php thinkphp,thi
- 下一篇: php用while循环做出1到10的乘积