Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a directory exists in PHP

Tags:

I know, I know, this sounds soo easy. But I can't seem to find the correct answer on the Internet.

One of the solution I found was to use is_dir.

if(is_dir($dir))   echo 'directory exists'; else   echo 'drectory not exist'; 

But this is wrong-- All this function does is to check whether the $dir is a directory, it doesn't check whether the directory exists, or not. In other words if I put:

$rootDir = "C:\\Documents and Settings\\test\\My Documents\\Image Directory\\Me Dog\\"; 

then the function will return a true, even though you can find no such directory on your web server.

Any ideas?

like image 997
Graviton Avatar asked Apr 14 '09 07:04

Graviton


People also ask

Is a directory in PHP?

The is_dir() function in PHP used to check whether the specified file is a directory or not. The name of the file is sent as a parameter to the is_dir() function and it returns True if the file is a directory else it returns False.

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.

Does exist in PHP?

PHP isset() FunctionThe isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

How do I open a directory in PHP?

PHP opendir() Function The opendir() function opens a directory handle.


1 Answers

Should work correctly. From is_dir() documentation:

Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Well, anyway if it doesn't try this:

if(file_exists($dir) && is_dir($dir)) 

BTW. results of these functions are cached in stat cache. Use clearstatcache() to clean that cache.

like image 85
vartec Avatar answered Sep 19 '22 20:09

vartec