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

前端 未结 22 2907
死守一世寂寞
死守一世寂寞 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:37

    all the answers here that use get_headers() are doing a GET request. It's much faster/cheaper to just do a HEAD request.

    To make sure that get_headers() does a HEAD request instead of a GET you should add this:

    stream_context_set_default(
        array(
            'http' => array(
                'method' => 'HEAD'
            )
        )
    );
    

    so to check if a file exists, your code would look something like this:

    stream_context_set_default(
        array(
            'http' => array(
                'method' => 'HEAD'
            )
        )
    );
    $headers = get_headers('http://website.com/dir/file.jpg', 1);
    $file_found = stristr($headers[0], '200');
    

    $file_found will return either false or true, obviously.

提交回复
热议问题