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

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

提交回复
热议问题