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

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

    A radical solution would be to display the favicons as background images in a div above your default icon. That way, all overhead would be placed on the client while still not displaying broken images (missing background images are ignored in all browsers AFAIK).

    0 讨论(0)
  • 2020-11-22 06:39
    function remote_file_exists($url){
       return(bool)preg_match('~HTTP/1\.\d\s+200\s+OK~', @current(get_headers($url)));
    }  
    $ff = "http://www.emeditor.com/pub/emed32_11.0.5.exe";
        if(remote_file_exists($ff)){
            echo "file exist!";
        }
        else{
            echo "file not exist!!!";
        }
    
    0 讨论(0)
  • 2020-11-22 06:39

    This works for me to check if a remote file exist in PHP:

    $url = 'https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico';
        $header_response = get_headers($url, 1);
    
        if ( strpos( $header_response[0], "404" ) !== false ) {
            echo 'File does NOT exist';
            } else {
            echo 'File exists';
            }
    
    0 讨论(0)
  • 2020-11-22 06:41

    PHP's inbuilt functions may not work for checking URL if allow_url_fopen setting is set to off for security reasons. Curl is a better option as we would not need to change our code at later stage. Below is the code I used to verify a valid URL:

    $url = str_replace(' ', '%20', $url);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);
    if($httpcode>=200 && $httpcode<300){  return true; } else { return false; } 
    

    Kindly note the CURLOPT_SSL_VERIFYPEER option which also verify the URL's starting with HTTPS.

    0 讨论(0)
提交回复
热议问题