我使用CURL来获得一个网站的状态,如果它是向上/向下或重定向到另一个网站。我想让它尽可能地精简,但它不太好用。
<?php
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode;
?>
我把这个包在一个函数里。它工作得很好,但性能不是最好的,因为它下载了整个页面,如果我删除$output = curl_exec($ch);它总是返回0。
有谁知道如何使表演更好吗?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$rt = curl_exec($ch);
$info = curl_getinfo($ch);
echo $info["http_code"];
使用这个hitCurl方法获取所有类型的api响应,即Get / Post
function hitCurl($url,$param = [],$type = 'POST'){
$ch = curl_init();
if(strtoupper($type) == 'GET'){
$param = http_build_query((array)$param);
$url = "{$url}?{$param}";
}else{
curl_setopt_array($ch,[
CURLOPT_POST => (strtoupper($type) == 'POST'),
CURLOPT_POSTFIELDS => (array)$param,
]);
}
curl_setopt_array($ch,[
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
]);
$resp = curl_exec($ch);
$statusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'statusCode' => $statusCode,
'resp' => $resp
];
}
用于测试api的演示函数
function fetchApiData(){
$url = 'https://postman-echo.com/get';
$resp = $this->hitCurl($url,[
'foo1'=>'bar1',
'foo2'=>'bar2'
],'get');
$apiData = "Getting header code {$resp['statusCode']}";
if($resp['statusCode'] == 200){
$apiData = json_decode($resp['resp']);
}
echo "<pre>";
print_r ($apiData);
echo "</pre>";
}