Php file_exists, does it really exists?

“Php functions are sometimes so confusing”, I don’t know how true that is, but I just found it to be true in this very case. Php’s file_exists, a function that seems like it is made to check if a file exists or not, is the one I encountered recently.

So I created this little test for this very purpose. I created an images folder with 2 files and 1 folder. Next I used file_exists function in 3 conditions with respective relative paths, to see which of those existed.

$file1="images/two.jpeg";
$file2="images/icon/one.jpg";
$file3="images/small/icon/";

if (file_exists($file1))
    echo "File one exists";

if (file_exists($file2))
    echo "File two exists";

if (file_exists($file3))
    echo "File three exists";

To my surprise all the conditions returned true.

File one exists
File two exists
File three exists

file_exists — Checks whether a file or directory exists.

According to php.net manual:

Irrespective of existence of file, file_exists function return true even if the path provided exists, which is in accordance with php manual’s definition, it’s just the name that is confusing. So, its better to use is_file() together with file_exists() if the objective is to check if the file really exists or is_dir()to check for directory.

Cheers!

Abhishek Gupta
Follow me
Latest posts by Abhishek Gupta (see all)

2 Replies to “Php file_exists, does it really exists?”

  1. I think the actual function you are trying to test is file_exists(),where as I see that you are using file_exits() which I dont think is a function of PHP

Leave a Reply