Perform a check on the presence of a resource before performing a processing
Working on external resources is never as simple as we think, because as long as the external resource really exists and is available for reading, there is never any problem in processing it, but when this is no longer reachable (for any reason), our processes get errors that somehow need to be handled.
To prevent any type of error due to the non-reachability of the requested file, we can use this function in order to verify the existence of a file before attempting to process it
<?php
function check_if_res_exists($file) {
$ch = curl_init($file);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$ret = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($ret == '200')
return true;
else
return false;
}
?>
calling it by entering the url of the file, this will return true or false depending on whether the file is located in the position we have indicated.
In this way we can anticipate any errors and reduce malfunctions of our software.