dismiss Step into the future! Click here to switch to the beta php.net site
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

is_executable> <glob
[edit] Last updated: Fri, 28 Jun 2013

view this page in

is_dir

(PHP 4, PHP 5)

is_dirTells whether the filename is a directory

Description

bool is_dir ( string $filename )

Tells whether the given filename is a directory.

Parameters

filename

Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled safe mode, or open_basedir further restrictions may apply.

Return Values

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

Examples

Example #1 is_dir() example

<?php
var_dump
(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));

var_dump(is_dir('..')); //one dir up
?>

The above example will output:

bool(false)
bool(false)
bool(true)

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note: The results of this function are cached. See clearstatcache() for more details.

Tip

As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

See Also

  • chdir() - Change directory
  • dir() - Return an instance of the Directory class
  • opendir() - Open directory handle
  • is_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link



is_executable> <glob
[edit] Last updated: Fri, 28 Jun 2013
 
add a note add a note User Contributed Notes is_dir - [43 notes]
up
4
Btx
4 years ago
<?php
public static function isEmptyDir($dir){
     return ((
$files = @scandir($dir)) && count($files) <= 2);
}
?>

better ;)
up
2
puremango dot co dot uk at gmail dot com
8 years ago
this function bypasses open_basedir restrictions.
<?
function my_is_dir($dir)
{
    // bypasses open_basedir restrictions of is_dir and fileperms
    $tmp_cmd = `ls -dl $dir`;
    $dir_flag = $tmp_cmd[0];
    if($dir_flag!="d")
    {
        // not d; use next char (first char might be 's' and is still directory)
        $dir_flag = $tmp_cmd[1];
    }
    return ($dir_flag=="d");
}
?>

example:
<?
....
echo is_dir("/somewhere/i/dont/have/access/to");
?>
output:
Warning: open_basedir restriction in effect

<?
....
echo my_is_dir("/somewhere/i/dont/have/access/to");
?>
output:
true (or false, depending whether it is or not...)

---
visit puremango.co.uk for other such wonders
up
2
danr at cvisual dot com dot com
5 years ago
Running PHP 5.2.0 on Apache Windows, I had a problem (likely the same one as described by others) where is_dir returned a False for directories with certain permissions even though they were accessible.

Strangely, I was able to overcome the problem with a more complete path. For example, this only displays "Works" on subdirectories with particular permissions (in this directory about 1 out of 3):

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        if(is_dir($f)) {
            echo "<b>Works:" . $f . "</b>";
        }
}

However, this works properly for all directories:

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        $dName = "./albums/mydir/" . $f;
        if(is_dir($dName)) {
            echo "<b>Works:" . $dName . "</b>";
        }
}

I don't understand the hit-and-miss of the first code, but maybe the second code can help others having this problem.
up
0
vstoykov at consultant dot bg
4 years ago
When trying (no 'pear') to enumerate mounted drives on a win32  platform (Win XP SP3, Apache/2.2.11, PHP/5.2.9), I used:

<?php
function echo_win_drives() {

  for(
$c='A'; $c<='Z'; $c++)
    if(
is_dir($c . ':'))
      echo
$c . ': ';
}
?>

which yielded:
A: C: D: E: F: G: H: I:
up
0
alanguir at detroitchamber dot com
4 years ago
When I run a scandir I always run a simple filter to account for file system artifacts (especially from a simple ftp folder drop) and the "." ".." that shows up in every directory:

<?php
   
if (is_dir($folder){
       
$contents = scandir($folder);
       
$bad = array(".", "..", ".DS_Store", "_notes", "Thumbs.db");
       
$files = array_diff($contents, $bad);
    }
?>
up
0
jasoneisen at gee mail
4 years ago
An even better (PHP 5 only) alternative to "Davy Defaud's function":

<?php
function is_empty_dir($dir)
{
    if ((
$files = @scandir($dir)) && count($files) <= 2) {
        return
true;
    }
    return
false;
}
?>

NOTE: you should obviously be checking beforehand if $dir is actually a directory, and that it is readable, as only relying on this you would assume that in both cases you have a non-empty readable directory.
up
0
Anonymous
5 years ago
On the previous example you may want to closedir() before returning, I tried the function and ran into some locking issues on windows when trying to delete the directory after I ran this function.
up
0
Anonymous
5 years ago
One note regarding checking for empty directories :
>>echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
This does not work correctly on Linux.
The '.' and '..' will always be returned even if no files are present in the directory.
up
0
gecko4 at gmail dot com
6 years ago
Here is another way to test if a directory is empty, which I think is much simpler than those posted below:

<?php
$dir
= 'directory';
echo (
count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>
up
0
Eric
6 years ago
Ah ha!  Maybe this is a bug, or limitation to be more precise, of php. See http://bugs.php.net/bug.php?id=27792

A workaround is posted on the page (above) and seems to work for me:

function is_dir_LFS($path){
  return (('d'==substr(exec("ls -dl '$path'"),0,1))?(true):(false));
}

PS: I'm using PHP 4.3.10-16, posts report this problem up to 5.0
up
0
alan dot rezende at light dot com dot br
6 years ago
The function is_dir will always return false if the handle acquired with opendir is not from the current working directory (getcwd); exception applies to "." and "..". Thus, if you need a consistent dir listing from any directory other than the current one, you must change dir first. Example follows:
<?php
chdir
( '..' );
$rep=opendir('.');
while (
false != ($file = readdir($rep))){
  if (
is_dir($file)){
    print(
"<a href='$file/' class='text1'>$file</a>");
  }
}
?>
The above code will list all directories (with links) for the ".." directory, relative to the current working dir.

THE WRONG WAY TO DO IT FOLLOWS:
<?php
$rep
=opendir('..');
while (
false != ($file = readdir($rep))){
 
//print "$file is here (may be a dir or not)<br>";
 
if (is_dir($file)){
    print
"<a href='$file/' class='text1'>$file</a><br>";
  }
}
?>
This code will turn into an empty list. If you want to make sure, uncomment the commented line...
Regards...
up
0
tibard at gmail dot com
8 years ago
use this function to get all files inside a directory (including subdirectories)

<?php
function scan_Dir($dir) {
   
$arrfiles = array();
    if (
is_dir($dir)) {
        if (
$handle = opendir($dir)) {
           
chdir($dir);
            while (
false !== ($file = readdir($handle))) {
                if (
$file != "." && $file != "..") {
                    if (
is_dir($file)) {
                       
$arr = scan_Dir($file);
                        foreach (
$arr as $value) {
                           
$arrfiles[] = $dir."/".$value;
                        }
                    } else {
                       
$arrfiles[] = $dir."/".$file;
                    }
                }
            }
           
chdir("../");
        }
       
closedir($handle);
    }
    return
$arrfiles;
}

?>
up
0
sly at noiretblanc dot org
9 years ago
This is the "is_dir" function I use to solve the problems :

function Another_is_dir ($file)
{
    if ((fileperms("$file") & 0x4000) == 0x4000)
        return TRUE;
    else
        return FALSE;
}

or, more simple :

function Another_is_dir ($file)
{
return ((fileperms("$file") & 0x4000) == 0x4000);
}

I can't remember where it comes from, but it works fine.
up
-1
John Doe
5 years ago
I altered the function below a bit. This implementation is simpler, faster and safer:

<?php
function is_empty_folder($folder) {
    if (!
is_dir($folder))
        return
false; // not a dir

   
$files = opendir($folder);
    while (
$file = readdir($files)) {
        if (
$file != '.' && $file != '..')
        return
true; // not empty
   
}
}
?>
up
-1
fanfatal at fanfatal dot pl
7 years ago
Hi
I wrote an usefull function to check is directory exists in directory's tree ;)

<?php
/*
 *    Function to check recursively if dirname is exists in directory's tree
 *
 *    @param string $dir_name
 *    @param string [$path]
 *    @return bool
 *    @author FanFataL
 */
function dir_exists($dir_name = false, $path = './') {
    if(!
$dir_name) return false;
   
    if(
is_dir($path.$dir_name)) return true;
   
   
$tree = glob($path.'*', GLOB_ONLYDIR);
    if(
$tree && count($tree)>0) {
        foreach(
$tree as $dir)
            if(
dir_exists($dir_name, $dir.'/'))
                return
true;
    }
   
    return
false;
}
?>

Greatings ;)
...
up
-1
akashif at freezone dot co dot uk
8 years ago
just a simple script to for those who dont have the IIS or Apache Dirlisting available , this will make onr for you

<?php
$DirPath
=$_GET['DirPath'];
if(
$DirPath=="")
{
   
$DirPath='./';
}
if ((
$handle=opendir($DirPath)))
{
    while (
$node = readdir($handle))
    {
       
$nodebase = basename($node);
        if (
$nodebase!="." && $nodebase!="..")
        {
            if(
is_dir($DirPath.$node))
            {
               
$nPath=$DirPath.$node."/";
                echo
"-> -> -> <a href='dir.php?DirPath=$nPath'>$node</a><br>";
            }
            else
            {
                echo
"<a href='$node'>$node</a><br>";
            }
        }
    }
}

?>
up
0
niceuser at live dot com
2 months ago
PITFALL in sub dir processing

After struggeling with a sub-dir processing (some subdirs were skipped) AND reading the posts, I realized that virutally no-one clearly told what were wrong.

The common traverse dir code was:
-----------------------------------------

opendir("myphotos"); // Top dir to process from (example)
 
while (false !== ($fname = readdir($h_dir))) { // process current dir (read a directory entry)

   if ($fname{0} == '.') continue; // skip dirs . and .. by first char test

   if (is_dir($fname)) call_own_subdir_process;  // process this subdir by calling a routine

   }

PROBLEM IS :

The "is_dir()" must have the FULL PATH or it will skip some dirs. So the above code need to INSERT THE PATH before the filename. This would give this change in above...

   if (is_dir("myphotos\" . $fname)) call_own_subdir_process;  // skip subdirs

The pitfall really was, that without full path some subdirs were found...hope this clears all up
up
0
Victor
3 months ago
If you are using Mac, or others systems that store information about the directory layout and etc, the function:

   function empty_dir($dir) {
        if (($files = @scandir($dir)) && count($files) <= 3)
            return true;
        else
            return false;
    }

Must have the count($files) comparing with the number of hidden files!

For example, I'm using Mac and the empty directory shows me three files: ".", ".." and ".DS_Store", so if I am planning to put the website online on my Mac, I've to count in the ".DS_Store" file!
up
-1
digitalaudiorock at gmail dot com
3 years ago
Just a note for anyone who encounters is_dir() returning false on CIFS mount points or directories within those mount points on 2.6.31 and newer kernels: Apparently in new kernels they've started using the CIFS serverino option by default.  With Windows shares this causes huge inode numbers and which apparently can cause is_dir() to return false.  Adding the noserverino option to the CIFS mount will prevent this.  This may only occur on 32 systems but I don't have a 64 bit install to test against.
up
-1
Davy Defaud
5 years ago
Well, "John Doe's function" doesn't return the good value when $file != '.' && $file != '..' it must return false and not true !
Moreover, as the latest contributor told us, the directory have to be closed before returning.
This one is far safer ;-) :

<?php
function is_empty_dir($dir)
{
    if (
$dh = @opendir($dir))
    {
        while (
$file = readdir($dh))
        {
            if (
$file != '.' && $file != '..') {
               
closedir($dh);
                return
false;
            }
        }
       
closedir($dh);
        return
true;
    }
    else return
false; // whatever the reason is : no such dir, not a dir, not readable
}
?>
up
-1
vlasec at gmailcom
5 years ago
zombix:
I don't know much about implementation, however I think that passing through all the files is useless. This code returns false also in case that it's not even a folder plus it stops in three steps at most.

<?php
function is_empty_folder($folder){
   
$c=0;
    if(
is_dir($folder) ){
       
$files = opendir($folder);
        while (
$file=readdir($files)){
           
$c++;
            if (
$c>2)
               return
false; // dir contains something
       
}
         return
true; // empty dir
   
}
    else return
false; // not a dir
}
?>
up
-1
sgoldbroch at DONTSPAMMEcmcplacce dot com
5 years ago
Took a while to figure this out, but - DONT USE THIS IN A LOOP WITH READDIR()!  readdir() only gives the file/dir name and not the full path which is_dir apparently needs to be able to accurately evaluate the argument.
up
-1
e dot loiseau at meteo-ondemand dot com
5 years ago
I had the same problem as others with not using the complete path to a folder when usin is_dir.

It's really important to use complete path.

$folder = "../pictures";
$dossier = opendir($folder);
while ($Fichier = readdir($dossier)) {
  if ($Fichier != "." && $Fichier != ".." && $Fichier != "Thumbs.db") {
//    if(is_dir($Fichier)) { // Do not always works
    if(is_dir($folder."/".$Fichier)) { // Works always
echo "$Fichier";
    } // fin if is file
  } // fin if restriction des fichiers à ne pas afficher
} // fin while
closedir($dossier);

Edouard
up
-1
legolas558 d0t users dot sf dot net
6 years ago
I had troubles at checking for the existance of a directory under the windows temporary path (usually c:\windows\temp\). I am using PHP 5.2.0

See also the bug tracker item: http://bugs.php.net/bug.php?id=39198

Here below the replacement function which works under the Windows temporary directory. It is a bad hack, since it creates and then removes the directory to verify its existance! But I could not find an alternative solution, that bug should be fixed.

<?php

function temp_is_dir($dir) {
   
// check directory existance under temp folder (tested on Windows)
    // see bug #31918 http://bugs.php.net/bug.php?id=39198
    // by legolas558
   
if (!@mkdir($dir))
        return
true;
   
rmdir($dir);
    return
false;
}
?>
up
-1
Anonymous
6 years ago
Be aware that is_dir() and is_file() will not work on very large (for me >2gb) files (also see http://de3.php.net/manual/en/function.is-file.php#56334).

You might try this approach - it works for me:

<?php
function isDir($dir) {
 
$cwd = getcwd();
 
$returnValue = false;
  if (@
chdir($dir)) {
   
chdir($cwd);
   
$returnValue = true;
  }
  return
$returnValue;
}
?>

Please keep in mind that isDir() will fail on directories which cannot be chdired due to permission settings for example.
up
-1
Eric Peterson
6 years ago
I'm not sure what is going on here... I have a function to return a listing of (sub)directories within a directory.  Works great until I ran into the directory given in the warning below... 87 characters seems too short to be running into a file/directory name length issue?

This is what I'm getting (though broken into a couple lines so this forum will accept it):

Warning: is_dir(): Stat failed for
/home/office/public_html/Library/1_NNHP-produced/4_Maps
/Peterson2003/BRTEreport_DVD.zip
(errno=75 - Value too large for defined data type) in /home/office/public_html/index.php on line 104

Here is line 104:

 if (is_dir($dir . "/" . $listing)) {
up
-1
locataweb at hotmail dot com
6 years ago
NOTE on Windows Shares (based on tests using PHP 5.1.1):

After many hours of head scratching and wondering why a script worked sometimes but not others, I discovered this revelation.

Be aware that base Windows shares are not recognised as dirs, so the following test will return false even if \\COMPUTER_NAME\SHARENAME exists.

<?php

if (is_dir('\\\\COMPUTER_NAME\\SHARENAME')) {
echo
"TRUE\n";
}
else {
echo
"FALSE\n";
}
//will return FALSE;

// However testing a subdir of the same base share
// using test below will return TRUE,
// despite the fact the parent base Windows share 
// returns false when tested by is_dir()

is_dir('\\\\COMPUTER_NAME\\SHARENAME\\SUBDIR') {
echo
"TRUE\n";
} else {
echo
"FALSE\n";
}
//will return TRUE.

?>

As a work round I replaced is_dir with is_readable() instead, which identifies if the share is readable and so must exist, but this is clearly dependent on whether the share is readable.

I hope this helps someone.  If there is a better work round or other purpose built solution to this problem with base windows shares, please post them so I'll know the next time.
up
-1
derek at nospam dot pmachine dot com
6 years ago
regarding dmertens-php-note at zyprexia dot com's statement on 24-Sep-2005 09:53

Actually, is_dir is not affected by UID checks in safe_mode.  is_dir will even return true if you lack sufficient privileges to read said directory.
up
-1
dmertens-php-note at zyprexia dot com
7 years ago
Remember that the owner of the directory has to be the same of the script user, otherwise this function will always return false when PHP is running in safe_mode..
up
-1
Anonymous
8 years ago
With error reporting set to all, and you attempt to do:
echo var_dump(is_dir('bogus_dir/abc'));

as output you will get:
Warning: stat failed for bogus_dir/abc (errno=2 - No such file or directory) in test.php on line 12
bool(false)

If you want to use this with an error reporting level set to all, you will need to use @ to supress the generated error
up
-1
renich at woralelandia dot com
8 years ago
Here goes a PHP5.0 link-to-directory listing function and examples

<?php

//List directories only
function list_dirs($path, $target)
{
   
$list = scandir($path);
   
    foreach (
$list as $number => $filename)
    {
        if (
$filename !== '.' && $filename !== '..' && is_dir("$path/$filename") )
        {
           
// Asign more readable and logic variables
           
$dir = $filename;
           
$url = apache_request_headers();
           
            if (
$target == '')
            {
               
// Print Dirs with link
               
print ("<a href=\"http://$url[Host]/$path/$dir\">$dir</a> <br>\n");
            }
            else
            {
               
// Print Dirs with link
               
print ("<a href=\"http://$url[Host]$dir\" target=\"$target\">$dir</a> <br>\n");
            }
               
        }
    }
}
   
?>

1.- List current directory's directories with no target property.

<?php

list_dirs
('.','')

?>

2.- List "libraries" in "pma2" located at my dir with a "_blank" target set

<?php

list_dirs
('pma2/libraries','_blank');

?>

or

<?php

list_dirs
('/var/www/html/pma2/libraries','_blank');

?>

3.- List all the directories located at the "/Home" dir with "_me" as target.

<?php

list_dirs
('/home', ''_me');

?>

I hope you all like it!

Note:
Obviously, the links will now work if the'
re not in the apache dir... ("htdocs", "html", "www", whatever)
up
-1
dusted19 at hotmail dot com
8 years ago
While working on a php project (my first one =( ).  I ran into a bug using is_dir() on my winxp w/ servicepack 2 system.  I'm using php 4.3.10.. the problem is whenever i pass is_dir() a pathname that is longer then 256 characters long it will ALWAYS return true.

CODE:

<?php

// Path to multimedia files
$mpath = "E:\\armoury\\";
ls($mpath);

//echo "MP3 Listing:<br/><br/>";

function ls ($curpath) {
  
$dir = dir($curpath);
   echo(
"<b>$curpath</b>");
   echo
"<blockquote>";
   while (
$file = $dir->read()) {
                    echo(
" <b>");
                    echo(
strlen($curpath.$file));
                    echo(
"</b> ");
            if(
$file != "." && $file != "..") {
                if (
is_dir($curpath.$file)) {
                   
ls($curpath.$file."\\");
                } else {
                    echo(
" $file<br>");
                }

            }

//       }
  
}
  
$dir->close();
   echo
"</blockquote>";
   return;
}

?>

This is the output.. the number preceding the file/directory is the number of characters in it's full path name.  You can see where it trips up at:

 257 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3

The pathname is greater then 256 characters.

229 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 07 - Bonita Applebum.mp3
227 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 08 - Can I Kick It.mp3
233 A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 09 - Youthful Expression.mp3
257 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\
259 260 267 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\index.php\
269 270 277 E:\armoury\[ hiphop - dub - reggae - soul ]\A Tribe Called Quest - 1990 - People's Instinctive Travels And The Paths Of Rhythm\A Tribe Called Quest - People's Instinctive Travels And The Paths Of Rhythm - 10 - Rhythm (Devoted To The Art Of Moving Butts).mp3\index.php\index.php\

Try it yourself on a large directory structure.
up
-1
Anonymous
8 years ago
Unfortunately, the function posted by p dot marzec at bold-sg dot pl does not work.
The corrected version is:

// returns true if folder is empty or not existing
// false if folde is full

function is_empty_folder($dir) {
if (is_dir($dir)) {
   $dl=opendir($dir);
   if ($dl) {
       while($name = readdir($dl)) {
   if (!is_dir("$dir/$name")) { //<--- corrected here
       return false;
       break;
       }
   }
       closedir($dl);
       }
   return true;
   } else return true;
}
up
-1
rchavezc at ameritech dot net
8 years ago
This is the function that I use to test for an empty directory:

<?php
function is_emtpy_dir($dirname){

// Returns true if  $dirname is a directory and it is empty

  
$result=false;                      // Assume it is not a directory
  
if(is_dir($dirname) ){
      
$result=true;                   // It is a directory
      
$handle = opendir($dirname);
       while( (
$name = readdir($handle)) !== false){
               if (
$name!= "." && $name !=".."){
            
$result=false;        // directory not empty
            
break;                   // no need to test more
          
}
       }
      
closedir($handle);
   }
   return
$result;
}
?>
up
-1
bhuskins at nospam dot christian-horizons dot org
8 years ago
'Is_empty_folder' posted by andreas at rueping dot net is a nice function. It did give me some grief, though. I don't beleive that it actually closes the directory when it's done (closedir in the wrong spot). I changed it slightly to be the following:

// returns true if folder is empty or not existing
// false if folde is full

<?
function is_emtpy_folder($folder){
   if(is_dir($folder) ){
       $handle = opendir($folder);
       while( (gettype( $name = readdir($handle)) != "boolean")){
               $name_array[] = $name;
       }
       foreach($name_array as $temp)
           $folder_content .= $temp;

       closedir($handle);//<--------moved this
       if($folder_content == "...") {
           return true;
       } else {
           return false;
       }
   }
   else
       return true; // folder doesnt exist
}
?>
up
-1
andreas at rueping dot net
9 years ago
function checks if a folder is empty or not. Retruns "true" if it is empty and "false" if it is full with data. Also if the folder doesnt even exist, function returns "true".

--------------------------------------------------
--------------------------------------------------

// returns true if folder is empty or not existing
// false if folde is full

<?
function is_emtpy_folder($folder){
    if(is_dir($folder) ){
        $handle = opendir($folder);
        while( (gettype( $name = readdir($handle)) != "boolean")){
                $name_array[] = $name;
        }
        foreach($name_array as $temp)
            $folder_content .= $temp;

        if($folder_content == "...")
            return true;
        else
            return false;
       
        closedir($handle);
    }
    else
        return true; // folder doesnt exist
}
?>
up
-2
p dot marzec at bold-sg dot pl
9 years ago
Simplest version 'is_empty_folder' posted by andreas at rueping dot net

// returns true if folder is empty or not existing
// false if folde is full

function is_empty_folder($dir) {
if (is_dir($dir)) {
    $dl=opendir($dir);
    if ($dl) {
        while($name = readdir($dl)) {
    if (!is_dir($name)) {
        return false;
        break;
        }
    }
        closedir($dl);
        }
    return true;
    } else return true;
}
up
-2
h_guillaume at hotmail dot com
2 years ago
I encoutered an error returning false on a directory, my problem was not a bug, but a bad relative path error inside the script function is_dir(), maybe it can help someone having the same problem.

I am using Linux with the folowing structure:
/var/www/vhosts/example.com/httpdocs/images/items_images/file1.jpg
/var/www/vhosts/example.com/httpdocs/images/items_images/temp

<?php
/* The folder "temp" will show as directory with the following script: */
$full_path = "/var/www/vhosts/example.com/httpdocs/images/items_images";
if (
$handle = opendir("$full_path")) {
    while (
false !== ($file = readdir($handle))) {
        if(
is_dir($full_path."/".$file)) continue;
        else echo
$file;
    }
}
?>

<?php
/* The folder "temp" will show as a file with the following script: */
$full_path = "/var/www/vhosts/example.com/httpdocs/images/items_images";
if (
$handle = opendir("$full_path")) {
    while (
false !== ($file = readdir($handle))) {
        if(
is_dir($file)) continue;
        else echo
$file;
    }
}
?>
up
-2
nielius at gmail dot com
5 years ago
@Anonymous:

If on Linux the suggested code does not work because '.' and '..' will allways be returned, it may be possible to subtract 2 from the amount of files found.
>>echo (count(glob("$dir/*") - 2) === 0) ? 'Empty' : 'Not
In that way, I think, you have solved the problem of two extra files that are counted.
up
-2
zombix at metrohive dot net
5 years ago
to check if folder is empty

function is_empty_folder($folder){
    $c=0;
    if(is_dir($folder) ){
        $files = opendir($folder);
        while ($file=readdir($files)){$c++;}
        if ($c>2){
            return false;
        }else{
            return true;
        }
    }       
}
up
-2
lordalderaan at gmail dot com
6 years ago
As was said earlier by locataweb at hotmail dot com is_dir returns false on windows shares even if they exist and are accessible.

I found that is_readable provides about the same functionality and does return true. It might provide a sufficient replacement in most cases.
up
-2
flobee
8 years ago
note: like the main example already shows. tooks me houres to understand und using chdir() to get a full dir scann (especilly on windows and "mounted" network drives)

never forget the tailing slash to find out if you have a directory or not.
<?php
function parse_dir($dir) {
    if (
$dh = @opendir($dir)) {
        while((
$file = readdir($dh)) !== false) {
            if( !
preg_match('/^\./s', $file) )  {
                if(
is_dir($dir.$file)) {
                   
$newdir = $dir.$file.'/'; // <- tailing slash
                   
chdir($newdir);
                    echo
"IS DIR: $newdir\n";
                    echo
parse_dir($newdir);
                } else {
                    echo
$dir.$file."\n";
                }
            }           
        }
       
chdir('..');
    }
}
parse_dir('z:/myfolder/mysubfolder/');

?>
up
-3
Trevor Pott
1 year ago
When attempting to list directories other than the one the script is located in, be aware of the peculiarities of is_dir's pathing requirements.

<?php
$dir   
=    ".";

if (
$handle = opendir($dir)) {
    while (
false !== ($entry = readdir($handle))) {
        if (
$entry != "." && $entry != "..") {
            if (
is_dir($entry) === true){
                echo
"DIRECTORY: ".$entry."\n";
            }else{
                echo
"FILE: ".$entry."\n";
            }
        }
    }
   
closedir($handle);
}
?>

Will work fine for the directory you are currently inhabiting...but no other one.

Instead, try this:
<?php
$dir   
=    "/some/other/dir";

if (
$handle = opendir($dir)) {
    while (
false !== ($entry = readdir($handle))) {
        if (
$entry != "." && $entry != "..") {
            if (
is_dir($dir."/".$entry) === true){
                echo
"DIRECTORY: ".$entry."\n";
            }else{
                echo
"FILE: ".$entry."\n";
            }
        }
    }
   
closedir($handle);
}

?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites