SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Get my greedy down dotJoon's Avatar
    Join Date
    Apr 2003
    Location
    daejeon, South Korea
    Posts
    2,223
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    $dir is empty or not.

    Code:
    if(is_dir($dir)){
    
    if(file_exists($dir.'/myFile.php')){ 
    
    echo "Yes, there is a file named myFile.php";
    }else{
    echo "No, myFile.php is not there.";
    }
    
    }
    The code above works file.

    The would-be code below doesn't work correctly, but I hope it shows what I want.

    Code:
    if(is_dir($dir)){
    
    if(file_exists($dir.'/'.*.*')){ 
    
    echo "Yes, there is a file or subDirectory at least one or more than one."
    }else{
    echo "No, its empty.";
    }
    
    }
    I like to get the directory is empty or NOT.

  2. #2
    SitePoint Member
    Join Date
    Jun 2010
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here are 2 simple functions to check if a directory is empty or not.

    Code:
    function is_dir_empty($dir) {
      if (!is_readable($dir)) return NULL; 
      return (count(scandir($dir)) == 2);
    }
    A better version

    Code:
    function is_dir_empty($dir) {
      if (!is_readable($dir)) return NULL; 
      $handle = opendir($dir);
      while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
          return FALSE;
        }
      }
      return TRUE;
    }
    You should find plenty of answers searching on google right away

  3. #3
    Get my greedy down dotJoon's Avatar
    Join Date
    Apr 2003
    Location
    daejeon, South Korea
    Posts
    2,223
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    The both code work fine each.
    Thank you very much, silv3r.m00n.

    By the way,
    Why does the 2nd function is the better version?
    (The 1st function is shorter and seems more understandable.)

  4. #4
    SitePoint Member
    Join Date
    Jun 2010
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    the first version uses scandir and hence checks all files in the directory. this will be slow if the directory has lots of file.

    since we just need to know if the directory is empty or not, its faster to check if the first file is other than "." and ".." (these are the directory paths actually to current directory and parent directory)
    that way if a file name is found other than "." and ".." using readdir, the entire list of files might not be read and the function would be faster.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •