【问题标题】:I want to check if a site is alive within this cURL code?我想检查一个站点在这个 cURL 代码中是否存在?
【发布时间】:2011-09-26 08:58:31
【问题描述】:

我使用此代码从其他服务器获取响应/结果,我想知道如何检查站点是否处于活动状态?

$ch = curl_init('http://domain.com/curl.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if (!$result)
// it will execute some codes if there is no result echoed from curl.php

【问题讨论】:

    标签: php curl


    【解决方案1】:

    您真正需要做的只是一个HEAD 请求,以查看重定向后是否收到200 OK 消息。 你不需要为此做一个完整的请求。事实上,你根本不应该。

    function check_alive($url, $timeout = 10) {
      $ch = curl_init($url);
    
      // Set request options
      curl_setopt_array($ch, array(
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_NOBODY => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_USERAGENT => "page-check/1.0" 
      ));
    
      // Execute request
      curl_exec($ch);
    
      // Check if an error occurred
      if(curl_errno($ch)) {
        curl_close($ch);
        return false;
      }
    
      // Get HTTP response code
      $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close($ch);
    
      // Page is alive if 200 OK is received
      return $code === 200;
    }
    

    【讨论】:

    • curl_getinfo($ch, CURLINFO_HTTP_CODE) 没有返回任何内容;当我运行相同的请求时,我得到 200 响应但使用 curl 我很无助,它是否仅在 curl_close($ch) 之后返回?
    【解决方案2】:

    这里比较简单

    <?php
    $yourUR="http://sitez.com";
    
    $handles = curl_init($yourUR);
    curl_setopt($handles, CURLOPT_NOBODY, true);
    curl_exec($handles);
    $resultat = curl_getinfo($handles, CURLINFO_HTTP_CODE);
    
    echo $resultat;
    ?>
    

    【讨论】:

      【解决方案3】:

      保持简短...

      $string = @file_get_contents('http://domain.com/curl.php');
      

      如果$stringnullempty,则该页面可能无法访问(或者实际上不输出任何内容)。

      【讨论】:

      • 我用 curl 来做,因为 curl.php 会输出 $result (就像一个特殊的键),它将返回到原始站点。如果 curl.php 没有打印任何内容,这意味着它没有工作或者没有输出任何内容?但我只想检查网站是否还活着而不处理 $result ..
      • -1:您不应该为此使用file_get_contents()。事实上,the recommended setting for allow_url_fopen is off[2]。再加上你正在发出一个完整的请求加上你无法控制超时......这确实是个坏主意。
      猜你喜欢
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多