I can't find a Drupal API function in D7 that tells me if an (unmanaged) file exists. D6 had a file_check_location but not for 7.
How to check if (unmanaged) file exists?
I can't find a Drupal API function in D7 that tells me if an (unmanaged) file exists. D6 had a file_check_location but not for 7.
How to check if (unmanaged) file exists?
You could just use the old bog standard PHP function file_exists()
if I understand you right:
$uri = 'public://images/an-image.jpg';
if (file_exists($uri)) {
// Do something
}
This also works for normal (absolute) paths as well, e.g.:
$path = '/var/www/drupal/sites/default/files/images/an-image.jpg';
if (file_exists($path)) {
// Do something
}
file_exists()
and it does not work. Any explanation?
If you want a Drupal way to do this, you can in Drupal 8/9/10 using the file_system service.
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$file_exists_error = $file_system->getDestinationFilename($file_uri, \Drupal\Core\File\FileSystemInterface::EXISTS_ERROR);
If the file does not exist in the file system $file_exists_error will return the file path, otherwise it will return false, denoting there was no error.
I don't know what your specific use case is, but you may not need to check to see if the file exists.
The functions file_unmanaged_copy, file_unmanaged_move, file_unmanaged_delete, file_unmanaged_delete_recursive, and file_unmanaged_save_data check to see if the file exists and return false if it does not.
You can find the source code in drupal/includes/file.inc and have a look.
You should use the drupal function:
file_destination($uri, FILE_EXISTS_ERROR)
and check
if (!file_destination($uri, FILE_EXISTS_ERROR)) {
// The file exist
// Do something
}
file_destination()
uses file_exists()
function
Commented
Mar 31, 2014 at 15:17