使用curl获取PHP中的HTTP代码


177

我正在使用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

有谁知道如何提高性能?

Answers:


259

首先确保URL实际上是有效的(字符串,不是空,语法不错),这可以快速检查服务器端。例如,首先执行此操作可以节省大量时间:

if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
    return false;
}

确保仅获取标题,而不获取正文内容:

@curl_setopt($ch, CURLOPT_HEADER  , true);  // we want headers
@curl_setopt($ch, CURLOPT_NOBODY  , true);  // we don't need body

有关获取URL状态http代码的更多详细信息,请参阅我发表的另一篇文章(它也有助于进行以下重定向):


整体而言:

$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;

4
我编辑了您的文章,并整体粘贴了示例代码。我发现这种方式更有帮助。顺便说一句,+ 1提及了CURLOPT_HEADER和CURLOPT_NOBODY设置!:)
Sk8erPeter

25
无需将CURLOPT_HEADER设置为true。您仍然可以通过curl_getinfo()获得HTTP代码。
Brainware'Mar

7
从PHP 5.5.0和cURL 7.10.8开始,此[CURLINFO_HTTP_CODE]是CURLINFO_RESPONSE_CODEref的旧别名
sshow

由于某种原因,这条线curl_setopt($ch, CURLOPT_NOBODY, true);挂了。不知道这是否与服务器的PHP版本有关。
itoctopus

126
// 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;

16
这是对这个问题的最直接答案
Enigma Plus

6
这不需要忽略身体,只需打一个电话,这也是我的首选答案。
Mike_K '17

24
$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"];

1
您输入了一个类型,应该为echo $ info [“ http_code”]; 而不是echo $ info [“ http_code];
Ludo-记录从


4

curl_getinfo —获取有关特定转账的信息

检查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);

2

curl_exec有必要的。尝试CURLOPT_NOBODY不下载正文。那可能更快。


0

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());

0

使用此hitCurl方法获取所有类型的api响应,即获取/发布

        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>";
    }

-3

这是我的解决方案需要获取Status 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);
}

1
与卷曲相比,Getheaders较慢。
Mike Kormendy '17

1
为什么不使用cron或webhook而不是使用sleep和endless loop?
Ugur Kazdal
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.