These both functions are used to check the existence of the file. But there is a minor difference between these functions.
Let’s see what’s the difference.
1) file_exists()
This function takes the path as a parameter and return [code]TRUE[/code] or [code]FALSE[/code]. This function will return TRUE in case of file exists and FALSE in case if file is not exists. Check below code for more details.
[cc lang=”php”]
$path =”/path/to/file/text.txt”;
if(file_exists($path))
echo “File Exists”;
else
echo “File not Exists”;
[/cc]
On more thing is that this function will return [code]TRUE[/code] if you pass the path for the valid directory also. Check below code,
[cc lang=”php”]
$path =”/path/to/file”;
if(file_exists($path))
echo “File Exists”;
else
echo “File not Exists”;
// This will return true if given path is a valid directory
[/cc]
2) is_file()
Unlike [code]file_exists()[/code], [code]is_file()[/code] function will check only for the valid files. If we pass the valid path to any directory then it will return [code]FALSE[/code].
Check below code:
[cc lang=”php”]
$path=/path/to/file/text.txt;
is_file($path);
// Return TRUE if valid file
$path=/path/to/directory;
is_file($path);
# Return FALSE every time
[/cc]
That’s why is_dir function exists..
Also worth noting is is_file is twice as fast, so it’s a good optimisation if you know it’s a real file you’re checking. Seems bizarre, but I guess file_exists actually runs multiple checks for possible scenarios, each of which might return true.