首页 > 解决方案 > 我们如何使用 Javascript 或 PHP 检查 URL 是否处于活动状态?

问题描述

我正在尝试使用 Javascript 和 PHP 检查 URL 是否处于活动状态(给出状态代码 200)。这是我正在尝试使用的代码。

使用 Javascript

var myRequest = new Request('https://www.google.com');
fetch(myRequest).then(function(response) {
  console.log(response.status); // returns 200
});

使用 PHP:

    <?php
function isValidUrl($url){
        $res = getHttpResponseCode_using_curl($url);
        //$res = getHttpResponseCode_using_getheaders($url);
        print_r($res);
        echo "<br>";
        if($res != 200){
            return false;
        }
        return true;
    }
function getHttpResponseCode_using_curl($url){
        if(! $url || ! is_string($url)){
            return false;
        }
        $ch = @curl_init($url);
        print_r($ch);
        echo "<br>";
        if($ch === false){
            return false;
        }
        @curl_setopt($ch, CURLOPT_HEADER         ,true);    // we want headers
        @curl_setopt($ch, CURLOPT_NOBODY         ,true);    // dont need body
        @curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true);    // catch output (do NOT print!)
        @curl_exec($ch);
        if(@curl_errno($ch)){   // should be 0
            @curl_close($ch);
            return false;
        }
        $code = @curl_getinfo($ch, CURLINFO_HTTP_CODE); 
        print_r($code);
        echo "<br>";
        @curl_close($ch);
        return $code;
    }
    
function getHttpResponseCode_using_getheaders($url){
        if(! $url || ! is_string($url)){
            return false;
        }
        $headers = @get_headers($url);
        print_r($headers);
        echo "<br>";
        if($headers && is_array($headers)){
            foreach($headers as $hline){
                if(preg_match('/^HTTP\/\S+\s+([1-9][0-9][0-9])\s+.*/', $hline, $matches) ){
                    $code = $matches[1];
                    return $code;
                }
            }
            return false;
        }
        return false;
    }
if(isValidUrl("https://www.google.com")){
    print_r("Running");
}else{
    print_r("Down");
}
?>

我尝试过 Ajax 调用以及尝试使用 @get_headers 方法来获取任何网站或 url 的状态代码!但是这些方法都没有给出任何网站的状态码。请帮忙。

标签: validationurl

解决方案


推荐阅读