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

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

    A complete function of the most voted answer:

    function remote_file_exists($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); # handles 301/2 redirects
        curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if( $httpCode == 200 ){return true;}
    }
    

    You can use it like this:

    if(remote_file_exists($url))
    {
        //file exists, do something
    }
    

提交回复
热议问题