is_file() vs file_exists()

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()

//first case: using file_exists()
foreach($images as $_image){
	$filePath = Mage::getBaseDir("media") . DS . str_replace("/", DS, $_image->getImagepath());
	if(file_exists($filePath)){
		echo '<img src="'.$filePath.'" alt="'.$_image->getTitle().'" border="0" />'; //display image
	}
}

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()

//second case: using is_file()
foreach($images as $_image){
	$filePath = Mage::getBaseDir("media") . DS . str_replace("/", DS, $_image->getImagepath());
	if(is_file($filePath)){
		echo '<img src="'.$filePath.'" alt="'.$_image->getTitle().'" border="0" />';
	}
}

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 🙂