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

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

    As Pies say you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.

    Here is example:

    function remoteFileExists($url) {
        $curl = curl_init($url);
    
        //don't fetch the actual page, you only want to check the connection is ok
        curl_setopt($curl, CURLOPT_NOBODY, true);
    
        //do request
        $result = curl_exec($curl);
    
        $ret = false;
    
        //if request did not fail
        if ($result !== false) {
            //if request was ok, check response code
            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  
    
            if ($statusCode == 200) {
                $ret = true;   
            }
        }
    
        curl_close($curl);
    
        return $ret;
    }
    
    $exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
    if ($exists) {
        echo 'file exists';
    } else {
        echo 'file does not exist';   
    }
    

提交回复
热议问题