SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Non-Member
    Join Date
    Feb 2010
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Checking if a folder is empty or not using PHP

    At times we need to check if a folder is empty or not before performing an operation on it. For this, I have written a function which returns TRUE if any file or folder is found inside the folder and FALSE if the folder is empty.

    function checkFolderIsEmptyOrNot ( $folderName ){
    $files = array ();
    if ( $handle = opendir ( $folderName ) ) {
    while ( false !== ( $file = readdir ( $handle ) ) ) {
    if ( $file != "." && $file != ".." ) {
    $files [] = $file;
    }
    }
    closedir ( $handle );
    }
    return ( count ( $files ) > 0 ) ? TRUE: FALSE;
    }
    Eliza

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    How about this? From the is_dir manual page.

    Code php:
    public static function isEmptyDir($dir){ 
         return (($files = @scandir($dir)) && count($files) <= 2); 
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your function is not bad either but why you continue reading all the files and folder if you found a file or folder in it. Just check as if a file found and terminate the loop with break.
    Code PHP:
    function checkFolderIsEmptyOrNot ( $folderName ){
        $files = array ();
        if ( $handle = opendir ( $folderName ) ) {
            while ( false !== ( $file = readdir ( $handle ) ) ) {
                if ( $file != "." && $file != ".." )
                    $files[] = $file;
                if(count($files) >= 1)
                    break;
            }
            closedir ( $handle );
        }
        return ( count ( $files ) > 0 ) ? TRUE: FALSE;
    }
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  4. #4
    SitePoint Evangelist AlienDev's Avatar
    Join Date
    Feb 2007
    Location
    UK
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    return (count(dir('here') === 2);
    Me on StackOverflow | Blog & personal website.

    I mostly use: PHP, Java, JavaScript, Android.


Tags for this Thread

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
  •