Avatar ·

How to check if a folder exists in PHP: is_dir, file_exists or both?

Hello everyone! I'm new to PHP and writing a script for uploading files to the server. I need to check if the directory where I will save files exists. If it doesn't — create it.

\n\n

I came across two functions: is_dir() and file_exists(). And now I don't understand which one to use. Here is my code:

\n\n
$path = '/uploads/images/';\n\n// Option 1\nif (is_dir($path)) {\n    echo "Folder exists";\n} else {\n    mkdir($path, 0777, true);\n}\n\n// Option 2\nif (file_exists($path)) {\n    echo "Folder exists";\n} else {\n    mkdir($path, 0777, true);\n}\n
\n\n

Both options seem to work, but I noticed some strange behavior. If I specify a path to a file rather than a folder, file_exists() returns true, while is_dir(