How can I check if a URL exists via PHP?

前端 未结 22 1214
天涯浪人
天涯浪人 2020-11-22 04:13

How do I check if a URL exists (not 404) in PHP?

22条回答
  •  渐次进展
    2020-11-22 05:00

    The best and simplest answer so far using get_headers() The best thing to check for string "200 ok". its far better than to check

    $file_headers = @get_headers($file-path);
    $file_headers[0];
    

    because sometime the array key numbers varies. so best thing is to check for "200 ok". Any URL which is up will have "200 ok" anywhere in get_headers() response.

    function url_exist($url) {
            $urlheaders = get_headers($url);
            //print_r($urlheaders);
            $urlmatches  = preg_grep('/200 ok/i', $urlheaders);
             if(!empty($urlmatches)){
               return true;
             }else{
               return false;
             }
    }
    

    now check the function if true or false

    if(url_exist(php-url-variable-here)
      URL exist
    }else{
      URL don't exist
    }
    

提交回复
热议问题