How can I check if a URL exists via PHP?

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

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

22条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 04:59

    All above solutions + extra sugar. (Ultimate AIO solution)

    /**
     * Check that given URL is valid and exists.
     * @param string $url URL to check
     * @return bool TRUE when valid | FALSE anyway
     */
    function urlExists ( $url ) {
        // Remove all illegal characters from a url
        $url = filter_var($url, FILTER_SANITIZE_URL);
    
        // Validate URI
        if (filter_var($url, FILTER_VALIDATE_URL) === FALSE
            // check only for http/https schemes.
            || !in_array(strtolower(parse_url($url, PHP_URL_SCHEME)), ['http','https'], true )
        ) {
            return false;
        }
    
        // Check that URL exists
        $file_headers = @get_headers($url);
        return !(!$file_headers || $file_headers[0] === 'HTTP/1.1 404 Not Found');
    }
    

    Example:

    var_dump ( urlExists('http://stackoverflow.com/') );
    // Output: true;
    

提交回复
热议问题