PHP: How to check if a remote file exists


Main method is read header file, so, you can read 2 article first:

PHP: How to get size of a remote file
PHP: How to get size of a remote file – Part 2

Here, we give some methods:

Method 1:

/**
 * @author tutorialspots.com
 * @copyright 2018
 */
function file_exists_remote($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_HEADER, true); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 120);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $r = curl_exec($curl); 
    curl_close($curl);
    return !($r===false || stripos($r,'404 not found')!==false);
}

Example:

var_dump(file_exists_remote('"http://tutorialspots.com/wp-content/uploads/2013/04/1.png"'));
var_dump(file_exists_remote('"http://tutorialspots.com/wp-content/uploads/2013/04/01.png"'));

Result:

bool(true) 
bool(false) 

Related Post

,

No comments yet.

Leave a Reply