Drupal - 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
}

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
} 

Tags:

Files

7