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
  • Clive to the rescue again, thanks! Can I hire you? ;-) – uwe Mar 2 '12 at 19:55
  • 6
    @MotoTribe Depends how much you're offering ;) – Clive Mar 2 '12 at 21:30
  • Why does this work? I just tested this with plain PHP and a stream handle thrown into file_exists() and it does not work. Any explanation? – kaiser May 31 '16 at 13:36
  • Because the streams have been properly registered by Drupal @kaiser. See php.net/manual/en/wrappers.php – Clive May 31 '16 at 13:39
  • @Clive I hoped you can point me to the source in Drupal. The rest I know and can not get working in a plain PHP test, hence I asked. Edit: nvm, found them – kaiser May 31 '16 at 14:03

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
  • 1
    It will work as file_destination() uses file_exists() function – milkovsky Mar 31 '14 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.