使用 curl 在 PHP 中获取 HTTP 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11797680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting HTTP code in PHP using curl
提问by Aaran McGuire
I'm using CURL to get the status of a site, if it's up/down or redirecting to another site. I want to get it as streamlined as possible, but it's not working well.
我正在使用 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;
?>
I have this wrapped in a function. It works fine but performance is not the best because it downloads the whole page, thing in if I remove $output = curl_exec($ch);it returns 0all the time.
我把它包装在一个函数中。它工作正常,但性能不是最好的,因为它会下载整个页面,如果我删除$output = curl_exec($ch);它,它总是会返回0。
Does anyone know how to make the performance better?
有谁知道如何使性能更好?
回答by MoonLite
First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:
首先确保 URL 是否实际有效(字符串,非空,良好的语法),这样可以快速检查服务器端。例如,先执行此操作可以节省大量时间:
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
return false;
}
Make sure you only fetch the headers, not the body content:
确保您只获取标题,而不是正文内容:
@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body
For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):
有关获取 URL 状态 http 代码的更多详细信息,我参考了我发表的另一篇文章(它也有助于以下重定向):
As a whole:
整体而言:
$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
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);
echo 'HTTP code: ' . $httpcode;
回答by Deepika Patel
// must set $url first....
$http = curl_init($url);
// do your curl thing here
$result = curl_exec($http);
$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);
curl_close($http);
echo $http_status;
回答by ntson1009
$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"];
回答by Raphael Caixeta
Try PHP's "get_headers" function.
试试 PHP 的“ get_headers”函数。
Something along the lines of:
类似的东西:
<?php
$url = 'http://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>
回答by Lead Developer
curl_getinfo— Get information regarding a specific transfer
curl_getinfo— 获取有关特定传输的信息
Check curl_getinfo
<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');
// Execute
curl_exec($ch);
// Check if any error occurred
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}
// Close handle
curl_close($ch);
回答by Explosion Pills
curl_execis necessary. Try CURLOPT_NOBODYto not download the body. That might be faster.
curl_exec是必要的。尽量CURLOPT_NOBODY不要下载正文。那可能会更快。
回答by mouhcine
function getStatusCode()
{
$url = 'example.com/test';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
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;
}
print_r(getStatusCode());
回答by Shamim
use this hitCurlmethod for fetch all type of api response i.e. Get / Post
使用此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
];
}
Demo function to test api
测试api的Demo函数
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>";
}
回答by christian Nguyen
Here is my solution need get Status Http for checking status of server regularly
这是我的解决方案需要获取状态 Http 以定期检查服务器的状态
$url = 'http://www.example.com'; // Your server link
while(true) {
$strHeader = get_headers($url)[0];
$statusCode = substr($strHeader, 9, 3 );
if($statusCode != 200 ) {
echo 'Server down.';
// Send email
}
else {
echo 'oK';
}
sleep(30);
}

