How can one check to see if a remote file exists using PHP?

前端 未结 22 2557
死守一世寂寞
死守一世寂寞 2020-11-22 05:52

The best I could find, an if fclose fopen type thing, makes the page load really slowly.

Basically what I\'m trying to do is

22条回答
  •  粉色の甜心
    2020-11-22 06:22

    If the file is not hosted external you might translate the remote URL to an absolute Path on your webserver. That way you don't have to call CURL or file_get_contents, etc.

    function remoteFileExists($url) {
    
        $root = realpath($_SERVER["DOCUMENT_ROOT"]);
        $urlParts = parse_url( $url );
    
        if ( !isset( $urlParts['path'] ) )
            return false;
    
        if ( is_file( $root . $urlParts['path'] ) )
            return true;
        else
            return false;
    
    }
    
    remoteFileExists( 'https://www.yourdomain.com/path/to/remote/image.png' );
    

    Note: Your webserver must populate DOCUMENT_ROOT to use this function

提交回复
热议问题