Introduction
If you do not know how to use is_file() and file_exists() properly, then you will end up pulling out your hair.
Here we will talk about a scenario which will clarify the usage of is_file() vs file_exists().
Case:
We are trying to show the gallery images from a table which has the field: ‘imagepath’ for storing the path of images.
And $images holds the array of gallery images.
1. Code using file_exists()
Notes: In this case <img> tag will be displayed in every loop even if $_image->getImagepath()
is empty. why?
file_exists
— Checks whether a file or directory exists
From the definition of file_exists(), it is clear that it checks whether a file or directory exists or not(don’t go with the name ‘file’ ;)).
In above case even if $_image->getImagepath()
is empty (i.e. file doesn’t exists), directory does exist as it points to Mage::getBaseDir("media"), file_exists($filePath)
always return true.
2. Code using is_file()
Notes: In this case <img> is displayed only if image file exists.
is_file — Tells whether the filename is a regular file
From the definition of is_file(), it is clear that if you want to check whether a file exists or not, is_file() seems to be the right choice.
So beware of using file_exists() while checking the existence of a file, is_file() is the right choice.
Hope this article makes some sense 🙂