curl 和 ping - 如何检查网站是打开还是关闭?

发布于 2024-10-10 16:19:25 字数 155 浏览 3 评论 0原文

我想使用 PHP 检查网站在特定实例上是否正常运行。我知道curl会获取文件的内容,但我不想阅读网站的内容。我只是想检查网站的状态。有什么办法可以检查网站的状态吗?我们可以使用 ping 来检查状态吗?对于我来说,从服务器获取状态信号(404、403 等)就足够了。一小段代码可能对我有很大帮助。

I want to check whether a website is up or down at a particular instance using PHP. I came to know that curl will fetch the contents of the file but I don't want to read the content of the website. I just want to check the status of the website. Is there any way to check the status of the site? Can we use ping to check the status? It is sufficient for me to get the status signals like (404, 403, etc) from the server. A small snippet of code might help me a lot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

倾城月光淡如水﹏ 2024-10-17 16:19:26
curl -Is $url | grep HTTP | cut -d ' ' -f2

curl -Is $url 仅输出标头。

grep HTTP 过滤 HTTP 响应标头。

cut -d ' ' -f2 将输出修剪为第二个“单词”,在本例中为状态代码。

例子:

$ curl -Is google.com | grep HTTP | cut -d ' ' -f2
301
curl -Is $url | grep HTTP | cut -d ' ' -f2

curl -Is $url outputs just the headers.

grep HTTP filters to the HTTP response header.

cut -d ' ' -f2 trims the output to the second "word", in this case the status code.

Example:

$ curl -Is google.com | grep HTTP | cut -d ' ' -f2
301
爱已欠费 2024-10-17 16:19:26
function checkStatus($url) {
    $agent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; pt-pt) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27";

    // initializes curl session
    $ch = curl_init();

    // sets the URL to fetch
    curl_setopt($ch, CURLOPT_URL, $url);

    // sets the content of the User-Agent header
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);

    // make sure you only check the header - taken from the answer above
    curl_setopt($ch, CURLOPT_NOBODY, true);

    // follow "Location: " redirects
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    // return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // disable output verbose information
    curl_setopt($ch, CURLOPT_VERBOSE, false);

    // max number of seconds to allow cURL function to execute
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    // execute
    curl_exec($ch);

    // get HTTP response code
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($httpcode >= 200 && $httpcode < 300)
        return true;
    else
        return false;
}
 
// how to use
//===================
if ($this->checkStatus("https://stackoverflow.com"))
    echo "Website is up";
else
    echo "Website is down";
exit;
function checkStatus($url) {
    $agent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; pt-pt) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27";

    // initializes curl session
    $ch = curl_init();

    // sets the URL to fetch
    curl_setopt($ch, CURLOPT_URL, $url);

    // sets the content of the User-Agent header
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);

    // make sure you only check the header - taken from the answer above
    curl_setopt($ch, CURLOPT_NOBODY, true);

    // follow "Location: " redirects
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    // return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // disable output verbose information
    curl_setopt($ch, CURLOPT_VERBOSE, false);

    // max number of seconds to allow cURL function to execute
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    // execute
    curl_exec($ch);

    // get HTTP response code
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($httpcode >= 200 && $httpcode < 300)
        return true;
    else
        return false;
}
 
// how to use
//===================
if ($this->checkStatus("https://stackoverflow.com"))
    echo "Website is up";
else
    echo "Website is down";
exit;
清风疏影 2024-10-17 16:19:26

我是这样做的。我设置了用户代理以尽量减少目标禁止我的可能性,并且还禁用了 SSL 验证,因为我知道目标:

private static function checkSite( $url ) {
    $useragent = $_SERVER['HTTP_USER_AGENT'];

    $options = array(
            CURLOPT_RETURNTRANSFER => true,      // return web page
            CURLOPT_HEADER         => false,     // do not return headers
            CURLOPT_FOLLOWLOCATION => true,      // follow redirects
            CURLOPT_USERAGENT      => $useragent, // who am i
            CURLOPT_AUTOREFERER    => true,       // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 2,          // timeout on connect (in seconds)
            CURLOPT_TIMEOUT        => 2,          // timeout on response (in seconds)
            CURLOPT_MAXREDIRS      => 10,         // stop after 10 redirects
            CURLOPT_SSL_VERIFYPEER => false,     // SSL verification not required
            CURLOPT_SSL_VERIFYHOST => false,     // SSL verification not required
    );
    $ch = curl_init( $url );
    curl_setopt_array( $ch, $options );
    curl_exec( $ch );

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($httpcode == 200);
}

Here is how I did it. I set the user agent to minimize the chance of the target banning me and also disabled SSL verification since I know the target:

private static function checkSite( $url ) {
    $useragent = $_SERVER['HTTP_USER_AGENT'];

    $options = array(
            CURLOPT_RETURNTRANSFER => true,      // return web page
            CURLOPT_HEADER         => false,     // do not return headers
            CURLOPT_FOLLOWLOCATION => true,      // follow redirects
            CURLOPT_USERAGENT      => $useragent, // who am i
            CURLOPT_AUTOREFERER    => true,       // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 2,          // timeout on connect (in seconds)
            CURLOPT_TIMEOUT        => 2,          // timeout on response (in seconds)
            CURLOPT_MAXREDIRS      => 10,         // stop after 10 redirects
            CURLOPT_SSL_VERIFYPEER => false,     // SSL verification not required
            CURLOPT_SSL_VERIFYHOST => false,     // SSL verification not required
    );
    $ch = curl_init( $url );
    curl_setopt_array( $ch, $options );
    curl_exec( $ch );

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($httpcode == 200);
}
懵少女 2024-10-17 16:19:26

你见过 get_headers() 函数吗? http://it.php.net/manual/en/function.get -headers.php 。它似乎完全符合您的需要。

如果直接使用带有 -I 标志的curl,它将返回 HTTP 标头(404 等)而不是页面 HTML。在 PHP 中,等效项是 curl_setopt($ch, CURLOPT_NOBODY, 1); 选项。

Have you seen the get_headers() function ? http://it.php.net/manual/en/function.get-headers.php . It seems to do exactly what you need.

If you use curl directly with the -I flag, it will return the HTTP headers (404 etc) instead of the page HTML. In PHP, the equivalent is the curl_setopt($ch, CURLOPT_NOBODY, 1); option.

葵雨 2024-10-17 16:19:26

ping 不会做您正在寻找的事情 - 它只会告诉您机器是否已启动(并响应 ping)。但这并不一定意味着网络服务器已经启动。

您可能想尝试使用 http_head 方法 - 它会检索网络服务器发回给您的标头。如果服务器发回标头,那么您就知道它已启动并正在运行。

ping won't do what you're looking for - it will only tell you if the machine is up (and responding to ping). That doesn't necessarily mean that the webserver is up, though.

You might want to try using the http_head method - it'll retrieve the headers that the webserver sends back to you. If the server is sending back headers, then you know it's up and running.

ぺ禁宫浮华殁 2024-10-17 16:19:26

您无法使用 ping 测试网络服务器,因为它是不同的服务。服务器可能会运行,但网络服务器守护程序可能会崩溃。所以curl是你的朋友。忽略内容即可。

You can not test a webserver with ping, because its a different service. The server may running, but the webserver-daemon may be crashed anyway. So curl is your friend. Just ignore the content.

难忘№最初的完美 2024-10-17 16:19:26

该函数检查 URL 是否存在。检查的时间最长为 300 毫秒,但您可以在 cURL 选项 CURLOPT_TIMEOUT_MS 中更改该参数。

/*
 * Check is URL exists
 *
 * @param  $url           Some URL
 * @param  $strict        You can add it true to check only HTTP 200 Response code
 *                        or you can add some custom response code like 302, 304 etc.
 *
 * @return boolean true or false
 */
function is_url_exists($url, $strict = false)
{
    if (is_int($strict) && $strict >= 100 && $strict < 600 || is_array($strict)) {
        if(is_array($strict)) {
            $response = $strict;
        } else {
            $response = [$strict];
        }
    } else if ($strict === true || $strict === 1) {
        $response = [200];
    } else {
        $response = [200,202,301,302,303];
    }
    $ch = curl_init( $url );
    
    $options = [
        CURLOPT_NOBODY          => true,
        CURLOPT_FAILONERROR     => true,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_NOSIGNAL        => true,
        CURLOPT_SSL_VERIFYPEER  => false,
        CURLOPT_SSL_VERIFYHOST  => false,
        CURLOPT_HEADER          => false,
        CURLOPT_FOLLOWLOCATION  => true,
        CURLOPT_VERBOSE         => false,
        CURLOPT_USERAGENT       => ( $_SERVER['HTTP_USER_AGENT'] ?? '' ),
        CURLOPT_TIMEOUT_MS      => 300, // TImeout in miliseconds
        CURLOPT_MAXREDIRS       => 2,
    ];
    
    curl_setopt_array($ch, $options);
    
    $return = curl_exec($ch);
    $errno = curl_errno($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    curl_close($ch);
    
    if (!$errno && $return !== false) {
        return ( in_array($httpcode, $response) !== false );
    }
    
    return false;
}

您可以检查任何 URL,从域、IP 地址到图像、文件等。我认为这是最快的方法并且被证明是有用的。

This function checks whether a URL exists or not. The time of the check is a maximum of 300ms, but you can change that parameter within the cURL option CURLOPT_TIMEOUT_MS

/*
 * Check is URL exists
 *
 * @param  $url           Some URL
 * @param  $strict        You can add it true to check only HTTP 200 Response code
 *                        or you can add some custom response code like 302, 304 etc.
 *
 * @return boolean true or false
 */
function is_url_exists($url, $strict = false)
{
    if (is_int($strict) && $strict >= 100 && $strict < 600 || is_array($strict)) {
        if(is_array($strict)) {
            $response = $strict;
        } else {
            $response = [$strict];
        }
    } else if ($strict === true || $strict === 1) {
        $response = [200];
    } else {
        $response = [200,202,301,302,303];
    }
    $ch = curl_init( $url );
    
    $options = [
        CURLOPT_NOBODY          => true,
        CURLOPT_FAILONERROR     => true,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_NOSIGNAL        => true,
        CURLOPT_SSL_VERIFYPEER  => false,
        CURLOPT_SSL_VERIFYHOST  => false,
        CURLOPT_HEADER          => false,
        CURLOPT_FOLLOWLOCATION  => true,
        CURLOPT_VERBOSE         => false,
        CURLOPT_USERAGENT       => ( $_SERVER['HTTP_USER_AGENT'] ?? '' ),
        CURLOPT_TIMEOUT_MS      => 300, // TImeout in miliseconds
        CURLOPT_MAXREDIRS       => 2,
    ];
    
    curl_setopt_array($ch, $options);
    
    $return = curl_exec($ch);
    $errno = curl_errno($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    curl_close($ch);
    
    if (!$errno && $return !== false) {
        return ( in_array($httpcode, $response) !== false );
    }
    
    return false;
}

You can check any URL, from domain, ip address to images, files, etc. I think this is the fastest way and proven useful.

清晨说晚安 2024-10-17 16:19:25

像这样的东西应该有效

    $url = 'yoururl';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_exec($ch);
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if (200==$retcode) {
        // All's well
    } else {
        // not so much
    }

something like this should work

    $url = 'yoururl';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_exec($ch);
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if (200==$retcode) {
        // All's well
    } else {
        // not so much
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文