You can easily check if a file exists using the PHP function file_exists(), but this function is limited to files within the same server. It will not work if you specify a location on a different domain. In that case you might want to use functions like file_get_contents(). Using these functions will download the whole file just to make sure that the file exists. This will take time and consume more memory. But this might not be what you want. You might just want to check if the file exists and not download it. In this post I have included a function with which you can do exactly the same.
The function downloads the header and checks the HTTP status to verify that the file specified by a URL actually exists. It uses curl to accomplish this. The PHP function file_exists_remote() is given below.
There is not much to explain in the function. It just sets the options, then make the request and then checks the response. If the file exists, it returns true, or else it will return false.
A simple PHP script that makes use of this function is given below.
In the above script, it is assumed that the function definition is included. Now go ahead and try this yourself. Please feel free to drop in any comments.
The function downloads the header and checks the HTTP status to verify that the file specified by a URL actually exists. It uses curl to accomplish this. The PHP function file_exists_remote() is given below.
<?php function file_exists_remote($url) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_NOBODY, true); //Check connection only $result = curl_exec($curl); //Actual request $ret = false; if ($result !== false) { $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); //Check HTTP status code if ($statusCode == 200) { $ret = true; } } curl_close($curl); return $ret; } ?>
There is not much to explain in the function. It just sets the options, then make the request and then checks the response. If the file exists, it returns true, or else it will return false.
A simple PHP script that makes use of this function is given below.
<?php $url = "http://www.example.com/picture.gif"; $exist = file_exists_remote($url); if($exist) { echo 'File Exists'; } else { echo 'File not found'; } ?>
In the above script, it is assumed that the function definition is included. Now go ahead and try this yourself. Please feel free to drop in any comments.
If the $url has spaces in the name of the image file then this code is redundant.
ReplyDeleteThanks for your interest in the article.
DeleteYou could use the "rawurlencode()" function in PHP to encode the URL before passing the URL to the function.
You may also add the following statement as the first line in the function to always perform this.
$url = rawurlencode($url);
this code works thank u so much
ReplyDelete