How can I check if a URL exists via PHP?

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

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

22条回答
  •  不要未来只要你来
    2020-11-22 05:02

    Here:

    $file = 'http://www.example.com/somefile.jpg';
    $file_headers = @get_headers($file);
    if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
        $exists = false;
    }
    else {
        $exists = true;
    }
    

    From here and right below the above post, there's a curl solution:

    function url_exists($url) {
        return curl_init($url) !== false;
    }
    

提交回复
热议问题