Search code examples
phpfile-iofile-get-contents

PHP to check file exist on external server using file_get_contents()


Checking file exists on external server using file_get_contents() method, does this method will work properly?

$url_file = "http://website.com/dir/filename.php";
$contents = file_get_contents($url_file);

if($contents){
echo "File Exists!";
} else {
echo "File Doesn't Exists!";
}

Solution

  • I think best method for me is using this script:

    $file = "http://website.com/dir/filename.php";
    $file_headers = get_headers($file);
    

    If file not exists output for $file_headers[0] is: HTTP/1.0 404 Not Found or HTTP/1.1 404 Not Found

    Use strpos method to check 404 string if file doesn't exists:

    if(strpos($file_headers[0], '404') !== false){
    echo "File Doesn't Exists!";
    } else {
    echo "File Exists!";
    }
    

    Thanks for all help :)