How can I use PHP to check if a directory is empty?












65















I am using the following script to read a directory. If there is no file in the directory it should say empty. The problem is, it just keeps saying the directory is empty even though there ARE files inside and vice versa.



<?php
$pid = $_GET["prodref"];
$dir = '/assets/'.$pid.'/v';
$q = (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';

if ($q=="Empty")
echo "the folder is empty";
else
echo "the folder is NOT empty";
?>









share|improve this question




















  • 8





    It's just a typo in your if statement. Use == (compare) instead of the single = (assign).

    – Bas Slagter
    Sep 21 '11 at 9:56
















65















I am using the following script to read a directory. If there is no file in the directory it should say empty. The problem is, it just keeps saying the directory is empty even though there ARE files inside and vice versa.



<?php
$pid = $_GET["prodref"];
$dir = '/assets/'.$pid.'/v';
$q = (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';

if ($q=="Empty")
echo "the folder is empty";
else
echo "the folder is NOT empty";
?>









share|improve this question




















  • 8





    It's just a typo in your if statement. Use == (compare) instead of the single = (assign).

    – Bas Slagter
    Sep 21 '11 at 9:56














65












65








65


22






I am using the following script to read a directory. If there is no file in the directory it should say empty. The problem is, it just keeps saying the directory is empty even though there ARE files inside and vice versa.



<?php
$pid = $_GET["prodref"];
$dir = '/assets/'.$pid.'/v';
$q = (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';

if ($q=="Empty")
echo "the folder is empty";
else
echo "the folder is NOT empty";
?>









share|improve this question
















I am using the following script to read a directory. If there is no file in the directory it should say empty. The problem is, it just keeps saying the directory is empty even though there ARE files inside and vice versa.



<?php
$pid = $_GET["prodref"];
$dir = '/assets/'.$pid.'/v';
$q = (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';

if ($q=="Empty")
echo "the folder is empty";
else
echo "the folder is NOT empty";
?>






php directory






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 11 '18 at 5:45







TheBlackBenzKid

















asked Sep 21 '11 at 9:44









TheBlackBenzKidTheBlackBenzKid

14.4k31112178




14.4k31112178








  • 8





    It's just a typo in your if statement. Use == (compare) instead of the single = (assign).

    – Bas Slagter
    Sep 21 '11 at 9:56














  • 8





    It's just a typo in your if statement. Use == (compare) instead of the single = (assign).

    – Bas Slagter
    Sep 21 '11 at 9:56








8




8





It's just a typo in your if statement. Use == (compare) instead of the single = (assign).

– Bas Slagter
Sep 21 '11 at 9:56





It's just a typo in your if statement. Use == (compare) instead of the single = (assign).

– Bas Slagter
Sep 21 '11 at 9:56












14 Answers
14






active

oldest

votes


















116














It seems that you need scandir instead of glob, as glob can't see unix hidden files.



<?php
$pid = basename($_GET["prodref"]); //let's sanitize it a bit
$dir = "/assets/$pid/v";

if (is_dir_empty($dir)) {
echo "the folder is empty";
}else{
echo "the folder is NOT empty";
}

function is_dir_empty($dir) {
if (!is_readable($dir)) return NULL;
return (count(scandir($dir)) == 2);
}
?>


Note that this code is not the summit of efficiency, as it's unnecessary to read all the files only to tell if directory is empty. So, the better version would be



function dir_is_empty($dir) {
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
closedir($handle);
return FALSE;
}
}
closedir($handle);
return TRUE;
}


By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An



a === b


expression already returns Empty or Non Empty in terms of programming language, FALSE or TRUE respectively - so, you can use the very result in control structures like IF() without any intermediate values






share|improve this answer





















  • 2





    I think both our code is wrong because I removed all files from the folder and it still says the folder is not empty... is there a way to check for hidden files like thumbs.db etc in linux??

    – TheBlackBenzKid
    Sep 21 '11 at 10:15













  • I think the FTP folder is say .. and . in the file is empty. How can I check if and remove the .. and thumbs.db etc??

    – TheBlackBenzKid
    Sep 21 '11 at 10:20











  • glob doesn't support linux hidden files. if you want them you have to go for openir solution like in the deleted answer

    – Your Common Sense
    Sep 21 '11 at 10:22











  • it seems you need scandir instead of glob.

    – Your Common Sense
    Sep 21 '11 at 10:25






  • 2





    Do create testing environment. create empty directory in the same folder where script is. make $dir = 'testfolder'; manually. then run this code. debug is printing out as much information as possible to see what is going wrong. $dir = 'testfolder';var_dump(scan_dir($dir)); will tell you what is in this directory

    – Your Common Sense
    Sep 21 '11 at 11:05



















59














I think using the FilesystemIterator should be the fastest and easiest way:



// PHP 5 >= 5.3.0
$iterator = new FilesystemIterator($dir);
$isDirEmpty = !$iterator->valid();


Or using class member access on instantiation:



// PHP 5 >= 5.4.0
$isDirEmpty = !(new FilesystemIterator($dir))->valid();


This works because a new FilesystemIterator will initially point to the first file in the folder - if there are no files in the folder, valid() will return false. (see documentation here.)



As pointed out by abdulmanov.ilmir, optionally check if the directory exists before using the FileSystemIterator because otherwise it'll throw an UnexpectedValueException.






share|improve this answer





















  • 5





    Mmm... tingling in my loins for this one.

    – Matt Fletcher
    Apr 25 '14 at 10:00











  • It works like a charm with elephant 5.3

    – userlond
    Sep 15 '15 at 6:42






  • 3





    You should consider that if $dir is not exists then an exception will be thrown.

    – abdulmanov.ilmir
    Nov 17 '17 at 9:55



















9














I found a quick solution



<?php
$dir = 'directory'; // dir path assign here
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>





share|improve this answer





















  • 1





    This code is working for me.

    – Ravi Patel
    Dec 26 '16 at 6:16











  • The solution I use in php 5.2 for simple case.

    – Lucas Morgan
    Jul 18 '17 at 14:44





















7














use



if ($q == "Empty")


instead of



if ($q="Empty")





share|improve this answer































    4














    Try this:



    <?php
    $dirPath = "Add your path here";

    $destdir = $dirPath;

    $handle = opendir($destdir);
    $c = 0;
    while ($file = readdir($handle)&& $c<3) {
    $c++;
    }

    if ($c>2) {
    print "Not empty";
    } else {
    print "Empty";
    }

    ?>





    share|improve this answer


























    • Thanks! I wrote it quite quickly and its my first post here @Piotr Nowicki

      – Drmzindec
      Nov 23 '11 at 10:13











    • Sure mate, it's just my civic duty ;-) Welcome to StackOverflow!

      – Piotr Nowicki
      Nov 23 '11 at 11:46



















    4














    Probably because of assignment operator in if statement.



    Change:



    if ($q="Empty")


    To:



    if ($q=="Empty")





    share|improve this answer

































      4














      This is a very old thread, but I thought I'd give my ten cents. The other solutions didn't work for me.



      Here is my solution:



      function is_dir_empty($dir) {
      foreach (new DirectoryIterator($dir) as $fileInfo) {
      if($fileInfo->isDot()) continue;
      return false;
      }
      return true;
      }


      Short and sweet. Works like a charm.






      share|improve this answer































        4














        For a object oriented approach using the RecursiveDirectoryIterator from the Standard PHP Library (SPL).



        <?php

        namespace MyFolder;

        use RecursiveDirectoryIterator;

        class FileHelper
        {
        /**
        * @param string $dir
        * @return bool
        */
        public static function isEmpty($dir)
        {
        $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
        return iterator_count($di) === 0;
        }
        }


        No need to make an instance of your FileHelper whenever you need it, you can access this static method wherever you need it like this:



        FileHelper::isEmpty($dir);


        The FileHelper class can be extended with other useful methods for copying, deleting, renaming, etc.



        There is no need to check the validity of the directory inside the method because if it is invalid the constructor of the RecursiveDirectoryIterator will throw an UnexpectedValueException which that covers that part sufficiently.






        share|improve this answer

































          2














          Just correct your code like this:



          <?php
          $pid = $_GET["prodref"];
          $dir = '/assets/'.$pid.'/v';
          $q = count(glob("$dir/*")) == 0;

          if ($q) {
          echo "the folder is empty";
          } else {
          echo "the folder is NOT empty";
          }
          ?>





          share|improve this answer

































            2














            @ Your Common Sense



            I think your performant example could be more performant using strict comparison:



            function is_dir_empty($dir) {
            if (!is_readable($dir)) return null;
            $handle = opendir($dir);
            while (false !== ($entry = readdir($handle))) {
            if ($entry !== '.' && $entry !== '..') { // <-- better use strict comparison here
            closedir($handle); // <-- always clean up! Close the directory stream
            return false;
            }
            }
            closedir($handle); // <-- always clean up! Close the directory stream
            return true;
            }





            share|improve this answer





















            • 1





              Good point regarding clean up: The return false case is not taking care of it ;-)

              – Beat Christen
              Sep 27 '16 at 13:02











            • @BeatChristen Thx for the hint! Fixed it.

              – André Fiedler
              Sep 28 '16 at 6:37











            • What I don't understand is why you say that it is better to use strict comparision when comparing to "." and "..". The readdir() function will always return a string (or the false) so I don't see the point. I'd also like to add that cleaning up after yourself is indeed always a good idea, one would think that after return when the $handle variable goes out of scope, closedir() would happen automatically but I just wrote a little test program, and it doesn't. Which is strange because other stuff, like flock do happen automatically.

              – soger
              Nov 20 '18 at 17:49



















            0














            I use this method in my Wordpress CSV 2 POST plugin.



                public function does_folder_contain_file_type( $path, $extension ){
            $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

            $html_files = new RegexIterator( $all_files, '/.'.$extension.'/' );

            foreach( $html_files as $file) {
            return true;// a file with $extension was found
            }

            return false;// no files with our extension found
            }


            It works by specific extension but is easily changed to suit your needs by removing "new RegexIterator(" line. Count $all_files.



                public function does_folder_contain_file_type( $path, $extension ){
            $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

            return count( $all_files );
            }





            share|improve this answer































              0














              I had a similar problem recently, although, the highest up-voted answer did not really work for me, hence, I had to come up with a similar solution. and again this may also not be the most efficient way to go about the problem,



              I created a function like so



              function is_empty_dir($dir)
              {
              if (is_dir($dir))
              {
              $objects = scandir($dir);
              foreach ($objects as $object)
              {
              if ($object != "." && $object != "..")
              {
              if (filetype($dir."/".$object) == "dir")
              {
              return false;
              } else {
              return false;
              }
              }
              }
              reset($objects);
              return true;
              }


              and used it to check for empty dricetory like so



              if(is_empty_dir($path)){
              rmdir($path);
              }





              share|improve this answer































                0














                You can use this:



                function isEmptyDir($dir)
                {
                return (($files = @scandir($dir)) && count($files) <= 2);
                }





                share|improve this answer































                  0














                  The first question is when is a directory empty? In a directory there are 2 files the '.' and '..'.

                  Next to that on a Mac there maybe the file '.DS_Store'. This file is created when some kind of content is added to the directory. If these 3 files are in the directory you may say the directory is empty.
                  So to test if a directory is empty (without testing if $dir is a directory):



                  function isDirEmpty( $dir ) {
                  $count = 0;
                  foreach (new DirectoryIterator( $dir ) as $fileInfo) {
                  if ( $fileInfo->isDot() || $fileInfo->getBasename() == '.DS_Store' ) {
                  continue;
                  }
                  $count++;
                  }
                  return ($count === 0);
                  }





                  share|improve this answer























                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7497733%2fhow-can-i-use-php-to-check-if-a-directory-is-empty%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    14 Answers
                    14






                    active

                    oldest

                    votes








                    14 Answers
                    14






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    116














                    It seems that you need scandir instead of glob, as glob can't see unix hidden files.



                    <?php
                    $pid = basename($_GET["prodref"]); //let's sanitize it a bit
                    $dir = "/assets/$pid/v";

                    if (is_dir_empty($dir)) {
                    echo "the folder is empty";
                    }else{
                    echo "the folder is NOT empty";
                    }

                    function is_dir_empty($dir) {
                    if (!is_readable($dir)) return NULL;
                    return (count(scandir($dir)) == 2);
                    }
                    ?>


                    Note that this code is not the summit of efficiency, as it's unnecessary to read all the files only to tell if directory is empty. So, the better version would be



                    function dir_is_empty($dir) {
                    $handle = opendir($dir);
                    while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                    closedir($handle);
                    return FALSE;
                    }
                    }
                    closedir($handle);
                    return TRUE;
                    }


                    By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An



                    a === b


                    expression already returns Empty or Non Empty in terms of programming language, FALSE or TRUE respectively - so, you can use the very result in control structures like IF() without any intermediate values






                    share|improve this answer





















                    • 2





                      I think both our code is wrong because I removed all files from the folder and it still says the folder is not empty... is there a way to check for hidden files like thumbs.db etc in linux??

                      – TheBlackBenzKid
                      Sep 21 '11 at 10:15













                    • I think the FTP folder is say .. and . in the file is empty. How can I check if and remove the .. and thumbs.db etc??

                      – TheBlackBenzKid
                      Sep 21 '11 at 10:20











                    • glob doesn't support linux hidden files. if you want them you have to go for openir solution like in the deleted answer

                      – Your Common Sense
                      Sep 21 '11 at 10:22











                    • it seems you need scandir instead of glob.

                      – Your Common Sense
                      Sep 21 '11 at 10:25






                    • 2





                      Do create testing environment. create empty directory in the same folder where script is. make $dir = 'testfolder'; manually. then run this code. debug is printing out as much information as possible to see what is going wrong. $dir = 'testfolder';var_dump(scan_dir($dir)); will tell you what is in this directory

                      – Your Common Sense
                      Sep 21 '11 at 11:05
















                    116














                    It seems that you need scandir instead of glob, as glob can't see unix hidden files.



                    <?php
                    $pid = basename($_GET["prodref"]); //let's sanitize it a bit
                    $dir = "/assets/$pid/v";

                    if (is_dir_empty($dir)) {
                    echo "the folder is empty";
                    }else{
                    echo "the folder is NOT empty";
                    }

                    function is_dir_empty($dir) {
                    if (!is_readable($dir)) return NULL;
                    return (count(scandir($dir)) == 2);
                    }
                    ?>


                    Note that this code is not the summit of efficiency, as it's unnecessary to read all the files only to tell if directory is empty. So, the better version would be



                    function dir_is_empty($dir) {
                    $handle = opendir($dir);
                    while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                    closedir($handle);
                    return FALSE;
                    }
                    }
                    closedir($handle);
                    return TRUE;
                    }


                    By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An



                    a === b


                    expression already returns Empty or Non Empty in terms of programming language, FALSE or TRUE respectively - so, you can use the very result in control structures like IF() without any intermediate values






                    share|improve this answer





















                    • 2





                      I think both our code is wrong because I removed all files from the folder and it still says the folder is not empty... is there a way to check for hidden files like thumbs.db etc in linux??

                      – TheBlackBenzKid
                      Sep 21 '11 at 10:15













                    • I think the FTP folder is say .. and . in the file is empty. How can I check if and remove the .. and thumbs.db etc??

                      – TheBlackBenzKid
                      Sep 21 '11 at 10:20











                    • glob doesn't support linux hidden files. if you want them you have to go for openir solution like in the deleted answer

                      – Your Common Sense
                      Sep 21 '11 at 10:22











                    • it seems you need scandir instead of glob.

                      – Your Common Sense
                      Sep 21 '11 at 10:25






                    • 2





                      Do create testing environment. create empty directory in the same folder where script is. make $dir = 'testfolder'; manually. then run this code. debug is printing out as much information as possible to see what is going wrong. $dir = 'testfolder';var_dump(scan_dir($dir)); will tell you what is in this directory

                      – Your Common Sense
                      Sep 21 '11 at 11:05














                    116












                    116








                    116







                    It seems that you need scandir instead of glob, as glob can't see unix hidden files.



                    <?php
                    $pid = basename($_GET["prodref"]); //let's sanitize it a bit
                    $dir = "/assets/$pid/v";

                    if (is_dir_empty($dir)) {
                    echo "the folder is empty";
                    }else{
                    echo "the folder is NOT empty";
                    }

                    function is_dir_empty($dir) {
                    if (!is_readable($dir)) return NULL;
                    return (count(scandir($dir)) == 2);
                    }
                    ?>


                    Note that this code is not the summit of efficiency, as it's unnecessary to read all the files only to tell if directory is empty. So, the better version would be



                    function dir_is_empty($dir) {
                    $handle = opendir($dir);
                    while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                    closedir($handle);
                    return FALSE;
                    }
                    }
                    closedir($handle);
                    return TRUE;
                    }


                    By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An



                    a === b


                    expression already returns Empty or Non Empty in terms of programming language, FALSE or TRUE respectively - so, you can use the very result in control structures like IF() without any intermediate values






                    share|improve this answer















                    It seems that you need scandir instead of glob, as glob can't see unix hidden files.



                    <?php
                    $pid = basename($_GET["prodref"]); //let's sanitize it a bit
                    $dir = "/assets/$pid/v";

                    if (is_dir_empty($dir)) {
                    echo "the folder is empty";
                    }else{
                    echo "the folder is NOT empty";
                    }

                    function is_dir_empty($dir) {
                    if (!is_readable($dir)) return NULL;
                    return (count(scandir($dir)) == 2);
                    }
                    ?>


                    Note that this code is not the summit of efficiency, as it's unnecessary to read all the files only to tell if directory is empty. So, the better version would be



                    function dir_is_empty($dir) {
                    $handle = opendir($dir);
                    while (false !== ($entry = readdir($handle))) {
                    if ($entry != "." && $entry != "..") {
                    closedir($handle);
                    return FALSE;
                    }
                    }
                    closedir($handle);
                    return TRUE;
                    }


                    By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An



                    a === b


                    expression already returns Empty or Non Empty in terms of programming language, FALSE or TRUE respectively - so, you can use the very result in control structures like IF() without any intermediate values







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 20 '18 at 5:36









                    Enyby

                    2,13511928




                    2,13511928










                    answered Sep 21 '11 at 9:52









                    Your Common SenseYour Common Sense

                    1




                    1








                    • 2





                      I think both our code is wrong because I removed all files from the folder and it still says the folder is not empty... is there a way to check for hidden files like thumbs.db etc in linux??

                      – TheBlackBenzKid
                      Sep 21 '11 at 10:15













                    • I think the FTP folder is say .. and . in the file is empty. How can I check if and remove the .. and thumbs.db etc??

                      – TheBlackBenzKid
                      Sep 21 '11 at 10:20











                    • glob doesn't support linux hidden files. if you want them you have to go for openir solution like in the deleted answer

                      – Your Common Sense
                      Sep 21 '11 at 10:22











                    • it seems you need scandir instead of glob.

                      – Your Common Sense
                      Sep 21 '11 at 10:25






                    • 2





                      Do create testing environment. create empty directory in the same folder where script is. make $dir = 'testfolder'; manually. then run this code. debug is printing out as much information as possible to see what is going wrong. $dir = 'testfolder';var_dump(scan_dir($dir)); will tell you what is in this directory

                      – Your Common Sense
                      Sep 21 '11 at 11:05














                    • 2





                      I think both our code is wrong because I removed all files from the folder and it still says the folder is not empty... is there a way to check for hidden files like thumbs.db etc in linux??

                      – TheBlackBenzKid
                      Sep 21 '11 at 10:15













                    • I think the FTP folder is say .. and . in the file is empty. How can I check if and remove the .. and thumbs.db etc??

                      – TheBlackBenzKid
                      Sep 21 '11 at 10:20











                    • glob doesn't support linux hidden files. if you want them you have to go for openir solution like in the deleted answer

                      – Your Common Sense
                      Sep 21 '11 at 10:22











                    • it seems you need scandir instead of glob.

                      – Your Common Sense
                      Sep 21 '11 at 10:25






                    • 2





                      Do create testing environment. create empty directory in the same folder where script is. make $dir = 'testfolder'; manually. then run this code. debug is printing out as much information as possible to see what is going wrong. $dir = 'testfolder';var_dump(scan_dir($dir)); will tell you what is in this directory

                      – Your Common Sense
                      Sep 21 '11 at 11:05








                    2




                    2





                    I think both our code is wrong because I removed all files from the folder and it still says the folder is not empty... is there a way to check for hidden files like thumbs.db etc in linux??

                    – TheBlackBenzKid
                    Sep 21 '11 at 10:15







                    I think both our code is wrong because I removed all files from the folder and it still says the folder is not empty... is there a way to check for hidden files like thumbs.db etc in linux??

                    – TheBlackBenzKid
                    Sep 21 '11 at 10:15















                    I think the FTP folder is say .. and . in the file is empty. How can I check if and remove the .. and thumbs.db etc??

                    – TheBlackBenzKid
                    Sep 21 '11 at 10:20





                    I think the FTP folder is say .. and . in the file is empty. How can I check if and remove the .. and thumbs.db etc??

                    – TheBlackBenzKid
                    Sep 21 '11 at 10:20













                    glob doesn't support linux hidden files. if you want them you have to go for openir solution like in the deleted answer

                    – Your Common Sense
                    Sep 21 '11 at 10:22





                    glob doesn't support linux hidden files. if you want them you have to go for openir solution like in the deleted answer

                    – Your Common Sense
                    Sep 21 '11 at 10:22













                    it seems you need scandir instead of glob.

                    – Your Common Sense
                    Sep 21 '11 at 10:25





                    it seems you need scandir instead of glob.

                    – Your Common Sense
                    Sep 21 '11 at 10:25




                    2




                    2





                    Do create testing environment. create empty directory in the same folder where script is. make $dir = 'testfolder'; manually. then run this code. debug is printing out as much information as possible to see what is going wrong. $dir = 'testfolder';var_dump(scan_dir($dir)); will tell you what is in this directory

                    – Your Common Sense
                    Sep 21 '11 at 11:05





                    Do create testing environment. create empty directory in the same folder where script is. make $dir = 'testfolder'; manually. then run this code. debug is printing out as much information as possible to see what is going wrong. $dir = 'testfolder';var_dump(scan_dir($dir)); will tell you what is in this directory

                    – Your Common Sense
                    Sep 21 '11 at 11:05













                    59














                    I think using the FilesystemIterator should be the fastest and easiest way:



                    // PHP 5 >= 5.3.0
                    $iterator = new FilesystemIterator($dir);
                    $isDirEmpty = !$iterator->valid();


                    Or using class member access on instantiation:



                    // PHP 5 >= 5.4.0
                    $isDirEmpty = !(new FilesystemIterator($dir))->valid();


                    This works because a new FilesystemIterator will initially point to the first file in the folder - if there are no files in the folder, valid() will return false. (see documentation here.)



                    As pointed out by abdulmanov.ilmir, optionally check if the directory exists before using the FileSystemIterator because otherwise it'll throw an UnexpectedValueException.






                    share|improve this answer





















                    • 5





                      Mmm... tingling in my loins for this one.

                      – Matt Fletcher
                      Apr 25 '14 at 10:00











                    • It works like a charm with elephant 5.3

                      – userlond
                      Sep 15 '15 at 6:42






                    • 3





                      You should consider that if $dir is not exists then an exception will be thrown.

                      – abdulmanov.ilmir
                      Nov 17 '17 at 9:55
















                    59














                    I think using the FilesystemIterator should be the fastest and easiest way:



                    // PHP 5 >= 5.3.0
                    $iterator = new FilesystemIterator($dir);
                    $isDirEmpty = !$iterator->valid();


                    Or using class member access on instantiation:



                    // PHP 5 >= 5.4.0
                    $isDirEmpty = !(new FilesystemIterator($dir))->valid();


                    This works because a new FilesystemIterator will initially point to the first file in the folder - if there are no files in the folder, valid() will return false. (see documentation here.)



                    As pointed out by abdulmanov.ilmir, optionally check if the directory exists before using the FileSystemIterator because otherwise it'll throw an UnexpectedValueException.






                    share|improve this answer





















                    • 5





                      Mmm... tingling in my loins for this one.

                      – Matt Fletcher
                      Apr 25 '14 at 10:00











                    • It works like a charm with elephant 5.3

                      – userlond
                      Sep 15 '15 at 6:42






                    • 3





                      You should consider that if $dir is not exists then an exception will be thrown.

                      – abdulmanov.ilmir
                      Nov 17 '17 at 9:55














                    59












                    59








                    59







                    I think using the FilesystemIterator should be the fastest and easiest way:



                    // PHP 5 >= 5.3.0
                    $iterator = new FilesystemIterator($dir);
                    $isDirEmpty = !$iterator->valid();


                    Or using class member access on instantiation:



                    // PHP 5 >= 5.4.0
                    $isDirEmpty = !(new FilesystemIterator($dir))->valid();


                    This works because a new FilesystemIterator will initially point to the first file in the folder - if there are no files in the folder, valid() will return false. (see documentation here.)



                    As pointed out by abdulmanov.ilmir, optionally check if the directory exists before using the FileSystemIterator because otherwise it'll throw an UnexpectedValueException.






                    share|improve this answer















                    I think using the FilesystemIterator should be the fastest and easiest way:



                    // PHP 5 >= 5.3.0
                    $iterator = new FilesystemIterator($dir);
                    $isDirEmpty = !$iterator->valid();


                    Or using class member access on instantiation:



                    // PHP 5 >= 5.4.0
                    $isDirEmpty = !(new FilesystemIterator($dir))->valid();


                    This works because a new FilesystemIterator will initially point to the first file in the folder - if there are no files in the folder, valid() will return false. (see documentation here.)



                    As pointed out by abdulmanov.ilmir, optionally check if the directory exists before using the FileSystemIterator because otherwise it'll throw an UnexpectedValueException.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 23 '17 at 14:11









                    mindplay.dk

                    4,95513240




                    4,95513240










                    answered Sep 17 '13 at 18:08









                    fluflu

                    10.2k75764




                    10.2k75764








                    • 5





                      Mmm... tingling in my loins for this one.

                      – Matt Fletcher
                      Apr 25 '14 at 10:00











                    • It works like a charm with elephant 5.3

                      – userlond
                      Sep 15 '15 at 6:42






                    • 3





                      You should consider that if $dir is not exists then an exception will be thrown.

                      – abdulmanov.ilmir
                      Nov 17 '17 at 9:55














                    • 5





                      Mmm... tingling in my loins for this one.

                      – Matt Fletcher
                      Apr 25 '14 at 10:00











                    • It works like a charm with elephant 5.3

                      – userlond
                      Sep 15 '15 at 6:42






                    • 3





                      You should consider that if $dir is not exists then an exception will be thrown.

                      – abdulmanov.ilmir
                      Nov 17 '17 at 9:55








                    5




                    5





                    Mmm... tingling in my loins for this one.

                    – Matt Fletcher
                    Apr 25 '14 at 10:00





                    Mmm... tingling in my loins for this one.

                    – Matt Fletcher
                    Apr 25 '14 at 10:00













                    It works like a charm with elephant 5.3

                    – userlond
                    Sep 15 '15 at 6:42





                    It works like a charm with elephant 5.3

                    – userlond
                    Sep 15 '15 at 6:42




                    3




                    3





                    You should consider that if $dir is not exists then an exception will be thrown.

                    – abdulmanov.ilmir
                    Nov 17 '17 at 9:55





                    You should consider that if $dir is not exists then an exception will be thrown.

                    – abdulmanov.ilmir
                    Nov 17 '17 at 9:55











                    9














                    I found a quick solution



                    <?php
                    $dir = 'directory'; // dir path assign here
                    echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
                    ?>





                    share|improve this answer





















                    • 1





                      This code is working for me.

                      – Ravi Patel
                      Dec 26 '16 at 6:16











                    • The solution I use in php 5.2 for simple case.

                      – Lucas Morgan
                      Jul 18 '17 at 14:44


















                    9














                    I found a quick solution



                    <?php
                    $dir = 'directory'; // dir path assign here
                    echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
                    ?>





                    share|improve this answer





















                    • 1





                      This code is working for me.

                      – Ravi Patel
                      Dec 26 '16 at 6:16











                    • The solution I use in php 5.2 for simple case.

                      – Lucas Morgan
                      Jul 18 '17 at 14:44
















                    9












                    9








                    9







                    I found a quick solution



                    <?php
                    $dir = 'directory'; // dir path assign here
                    echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
                    ?>





                    share|improve this answer















                    I found a quick solution



                    <?php
                    $dir = 'directory'; // dir path assign here
                    echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
                    ?>






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 1 '17 at 7:04

























                    answered Oct 8 '13 at 8:49









                    FrankFrank

                    1,12772956




                    1,12772956








                    • 1





                      This code is working for me.

                      – Ravi Patel
                      Dec 26 '16 at 6:16











                    • The solution I use in php 5.2 for simple case.

                      – Lucas Morgan
                      Jul 18 '17 at 14:44
















                    • 1





                      This code is working for me.

                      – Ravi Patel
                      Dec 26 '16 at 6:16











                    • The solution I use in php 5.2 for simple case.

                      – Lucas Morgan
                      Jul 18 '17 at 14:44










                    1




                    1





                    This code is working for me.

                    – Ravi Patel
                    Dec 26 '16 at 6:16





                    This code is working for me.

                    – Ravi Patel
                    Dec 26 '16 at 6:16













                    The solution I use in php 5.2 for simple case.

                    – Lucas Morgan
                    Jul 18 '17 at 14:44







                    The solution I use in php 5.2 for simple case.

                    – Lucas Morgan
                    Jul 18 '17 at 14:44













                    7














                    use



                    if ($q == "Empty")


                    instead of



                    if ($q="Empty")





                    share|improve this answer




























                      7














                      use



                      if ($q == "Empty")


                      instead of



                      if ($q="Empty")





                      share|improve this answer


























                        7












                        7








                        7







                        use



                        if ($q == "Empty")


                        instead of



                        if ($q="Empty")





                        share|improve this answer













                        use



                        if ($q == "Empty")


                        instead of



                        if ($q="Empty")






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Sep 21 '11 at 9:48









                        TotoToto

                        65.2k175698




                        65.2k175698























                            4














                            Try this:



                            <?php
                            $dirPath = "Add your path here";

                            $destdir = $dirPath;

                            $handle = opendir($destdir);
                            $c = 0;
                            while ($file = readdir($handle)&& $c<3) {
                            $c++;
                            }

                            if ($c>2) {
                            print "Not empty";
                            } else {
                            print "Empty";
                            }

                            ?>





                            share|improve this answer


























                            • Thanks! I wrote it quite quickly and its my first post here @Piotr Nowicki

                              – Drmzindec
                              Nov 23 '11 at 10:13











                            • Sure mate, it's just my civic duty ;-) Welcome to StackOverflow!

                              – Piotr Nowicki
                              Nov 23 '11 at 11:46
















                            4














                            Try this:



                            <?php
                            $dirPath = "Add your path here";

                            $destdir = $dirPath;

                            $handle = opendir($destdir);
                            $c = 0;
                            while ($file = readdir($handle)&& $c<3) {
                            $c++;
                            }

                            if ($c>2) {
                            print "Not empty";
                            } else {
                            print "Empty";
                            }

                            ?>





                            share|improve this answer


























                            • Thanks! I wrote it quite quickly and its my first post here @Piotr Nowicki

                              – Drmzindec
                              Nov 23 '11 at 10:13











                            • Sure mate, it's just my civic duty ;-) Welcome to StackOverflow!

                              – Piotr Nowicki
                              Nov 23 '11 at 11:46














                            4












                            4








                            4







                            Try this:



                            <?php
                            $dirPath = "Add your path here";

                            $destdir = $dirPath;

                            $handle = opendir($destdir);
                            $c = 0;
                            while ($file = readdir($handle)&& $c<3) {
                            $c++;
                            }

                            if ($c>2) {
                            print "Not empty";
                            } else {
                            print "Empty";
                            }

                            ?>





                            share|improve this answer















                            Try this:



                            <?php
                            $dirPath = "Add your path here";

                            $destdir = $dirPath;

                            $handle = opendir($destdir);
                            $c = 0;
                            while ($file = readdir($handle)&& $c<3) {
                            $c++;
                            }

                            if ($c>2) {
                            print "Not empty";
                            } else {
                            print "Empty";
                            }

                            ?>






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 23 '11 at 10:14

























                            answered Nov 22 '11 at 12:11









                            DrmzindecDrmzindec

                            712




                            712













                            • Thanks! I wrote it quite quickly and its my first post here @Piotr Nowicki

                              – Drmzindec
                              Nov 23 '11 at 10:13











                            • Sure mate, it's just my civic duty ;-) Welcome to StackOverflow!

                              – Piotr Nowicki
                              Nov 23 '11 at 11:46



















                            • Thanks! I wrote it quite quickly and its my first post here @Piotr Nowicki

                              – Drmzindec
                              Nov 23 '11 at 10:13











                            • Sure mate, it's just my civic duty ;-) Welcome to StackOverflow!

                              – Piotr Nowicki
                              Nov 23 '11 at 11:46

















                            Thanks! I wrote it quite quickly and its my first post here @Piotr Nowicki

                            – Drmzindec
                            Nov 23 '11 at 10:13





                            Thanks! I wrote it quite quickly and its my first post here @Piotr Nowicki

                            – Drmzindec
                            Nov 23 '11 at 10:13













                            Sure mate, it's just my civic duty ;-) Welcome to StackOverflow!

                            – Piotr Nowicki
                            Nov 23 '11 at 11:46





                            Sure mate, it's just my civic duty ;-) Welcome to StackOverflow!

                            – Piotr Nowicki
                            Nov 23 '11 at 11:46











                            4














                            Probably because of assignment operator in if statement.



                            Change:



                            if ($q="Empty")


                            To:



                            if ($q=="Empty")





                            share|improve this answer






























                              4














                              Probably because of assignment operator in if statement.



                              Change:



                              if ($q="Empty")


                              To:



                              if ($q=="Empty")





                              share|improve this answer




























                                4












                                4








                                4







                                Probably because of assignment operator in if statement.



                                Change:



                                if ($q="Empty")


                                To:



                                if ($q=="Empty")





                                share|improve this answer















                                Probably because of assignment operator in if statement.



                                Change:



                                if ($q="Empty")


                                To:



                                if ($q=="Empty")






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Aug 4 '13 at 18:20









                                Benjamin

                                15.7k28120231




                                15.7k28120231










                                answered Sep 21 '11 at 9:48









                                RobikRobik

                                4,97732641




                                4,97732641























                                    4














                                    This is a very old thread, but I thought I'd give my ten cents. The other solutions didn't work for me.



                                    Here is my solution:



                                    function is_dir_empty($dir) {
                                    foreach (new DirectoryIterator($dir) as $fileInfo) {
                                    if($fileInfo->isDot()) continue;
                                    return false;
                                    }
                                    return true;
                                    }


                                    Short and sweet. Works like a charm.






                                    share|improve this answer




























                                      4














                                      This is a very old thread, but I thought I'd give my ten cents. The other solutions didn't work for me.



                                      Here is my solution:



                                      function is_dir_empty($dir) {
                                      foreach (new DirectoryIterator($dir) as $fileInfo) {
                                      if($fileInfo->isDot()) continue;
                                      return false;
                                      }
                                      return true;
                                      }


                                      Short and sweet. Works like a charm.






                                      share|improve this answer


























                                        4












                                        4








                                        4







                                        This is a very old thread, but I thought I'd give my ten cents. The other solutions didn't work for me.



                                        Here is my solution:



                                        function is_dir_empty($dir) {
                                        foreach (new DirectoryIterator($dir) as $fileInfo) {
                                        if($fileInfo->isDot()) continue;
                                        return false;
                                        }
                                        return true;
                                        }


                                        Short and sweet. Works like a charm.






                                        share|improve this answer













                                        This is a very old thread, but I thought I'd give my ten cents. The other solutions didn't work for me.



                                        Here is my solution:



                                        function is_dir_empty($dir) {
                                        foreach (new DirectoryIterator($dir) as $fileInfo) {
                                        if($fileInfo->isDot()) continue;
                                        return false;
                                        }
                                        return true;
                                        }


                                        Short and sweet. Works like a charm.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Aug 13 '15 at 6:32









                                        narfienarfie

                                        1811110




                                        1811110























                                            4














                                            For a object oriented approach using the RecursiveDirectoryIterator from the Standard PHP Library (SPL).



                                            <?php

                                            namespace MyFolder;

                                            use RecursiveDirectoryIterator;

                                            class FileHelper
                                            {
                                            /**
                                            * @param string $dir
                                            * @return bool
                                            */
                                            public static function isEmpty($dir)
                                            {
                                            $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
                                            return iterator_count($di) === 0;
                                            }
                                            }


                                            No need to make an instance of your FileHelper whenever you need it, you can access this static method wherever you need it like this:



                                            FileHelper::isEmpty($dir);


                                            The FileHelper class can be extended with other useful methods for copying, deleting, renaming, etc.



                                            There is no need to check the validity of the directory inside the method because if it is invalid the constructor of the RecursiveDirectoryIterator will throw an UnexpectedValueException which that covers that part sufficiently.






                                            share|improve this answer






























                                              4














                                              For a object oriented approach using the RecursiveDirectoryIterator from the Standard PHP Library (SPL).



                                              <?php

                                              namespace MyFolder;

                                              use RecursiveDirectoryIterator;

                                              class FileHelper
                                              {
                                              /**
                                              * @param string $dir
                                              * @return bool
                                              */
                                              public static function isEmpty($dir)
                                              {
                                              $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
                                              return iterator_count($di) === 0;
                                              }
                                              }


                                              No need to make an instance of your FileHelper whenever you need it, you can access this static method wherever you need it like this:



                                              FileHelper::isEmpty($dir);


                                              The FileHelper class can be extended with other useful methods for copying, deleting, renaming, etc.



                                              There is no need to check the validity of the directory inside the method because if it is invalid the constructor of the RecursiveDirectoryIterator will throw an UnexpectedValueException which that covers that part sufficiently.






                                              share|improve this answer




























                                                4












                                                4








                                                4







                                                For a object oriented approach using the RecursiveDirectoryIterator from the Standard PHP Library (SPL).



                                                <?php

                                                namespace MyFolder;

                                                use RecursiveDirectoryIterator;

                                                class FileHelper
                                                {
                                                /**
                                                * @param string $dir
                                                * @return bool
                                                */
                                                public static function isEmpty($dir)
                                                {
                                                $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
                                                return iterator_count($di) === 0;
                                                }
                                                }


                                                No need to make an instance of your FileHelper whenever you need it, you can access this static method wherever you need it like this:



                                                FileHelper::isEmpty($dir);


                                                The FileHelper class can be extended with other useful methods for copying, deleting, renaming, etc.



                                                There is no need to check the validity of the directory inside the method because if it is invalid the constructor of the RecursiveDirectoryIterator will throw an UnexpectedValueException which that covers that part sufficiently.






                                                share|improve this answer















                                                For a object oriented approach using the RecursiveDirectoryIterator from the Standard PHP Library (SPL).



                                                <?php

                                                namespace MyFolder;

                                                use RecursiveDirectoryIterator;

                                                class FileHelper
                                                {
                                                /**
                                                * @param string $dir
                                                * @return bool
                                                */
                                                public static function isEmpty($dir)
                                                {
                                                $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
                                                return iterator_count($di) === 0;
                                                }
                                                }


                                                No need to make an instance of your FileHelper whenever you need it, you can access this static method wherever you need it like this:



                                                FileHelper::isEmpty($dir);


                                                The FileHelper class can be extended with other useful methods for copying, deleting, renaming, etc.



                                                There is no need to check the validity of the directory inside the method because if it is invalid the constructor of the RecursiveDirectoryIterator will throw an UnexpectedValueException which that covers that part sufficiently.







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Apr 12 '16 at 15:39

























                                                answered Apr 12 '16 at 12:50









                                                WiltWilt

                                                21.2k887127




                                                21.2k887127























                                                    2














                                                    Just correct your code like this:



                                                    <?php
                                                    $pid = $_GET["prodref"];
                                                    $dir = '/assets/'.$pid.'/v';
                                                    $q = count(glob("$dir/*")) == 0;

                                                    if ($q) {
                                                    echo "the folder is empty";
                                                    } else {
                                                    echo "the folder is NOT empty";
                                                    }
                                                    ?>





                                                    share|improve this answer






























                                                      2














                                                      Just correct your code like this:



                                                      <?php
                                                      $pid = $_GET["prodref"];
                                                      $dir = '/assets/'.$pid.'/v';
                                                      $q = count(glob("$dir/*")) == 0;

                                                      if ($q) {
                                                      echo "the folder is empty";
                                                      } else {
                                                      echo "the folder is NOT empty";
                                                      }
                                                      ?>





                                                      share|improve this answer




























                                                        2












                                                        2








                                                        2







                                                        Just correct your code like this:



                                                        <?php
                                                        $pid = $_GET["prodref"];
                                                        $dir = '/assets/'.$pid.'/v';
                                                        $q = count(glob("$dir/*")) == 0;

                                                        if ($q) {
                                                        echo "the folder is empty";
                                                        } else {
                                                        echo "the folder is NOT empty";
                                                        }
                                                        ?>





                                                        share|improve this answer















                                                        Just correct your code like this:



                                                        <?php
                                                        $pid = $_GET["prodref"];
                                                        $dir = '/assets/'.$pid.'/v';
                                                        $q = count(glob("$dir/*")) == 0;

                                                        if ($q) {
                                                        echo "the folder is empty";
                                                        } else {
                                                        echo "the folder is NOT empty";
                                                        }
                                                        ?>






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Sep 9 '13 at 11:52









                                                        nhahtdh

                                                        47.6k1291130




                                                        47.6k1291130










                                                        answered Sep 9 '13 at 9:48









                                                        Alessandro.VegnaAlessandro.Vegna

                                                        1,071816




                                                        1,071816























                                                            2














                                                            @ Your Common Sense



                                                            I think your performant example could be more performant using strict comparison:



                                                            function is_dir_empty($dir) {
                                                            if (!is_readable($dir)) return null;
                                                            $handle = opendir($dir);
                                                            while (false !== ($entry = readdir($handle))) {
                                                            if ($entry !== '.' && $entry !== '..') { // <-- better use strict comparison here
                                                            closedir($handle); // <-- always clean up! Close the directory stream
                                                            return false;
                                                            }
                                                            }
                                                            closedir($handle); // <-- always clean up! Close the directory stream
                                                            return true;
                                                            }





                                                            share|improve this answer





















                                                            • 1





                                                              Good point regarding clean up: The return false case is not taking care of it ;-)

                                                              – Beat Christen
                                                              Sep 27 '16 at 13:02











                                                            • @BeatChristen Thx for the hint! Fixed it.

                                                              – André Fiedler
                                                              Sep 28 '16 at 6:37











                                                            • What I don't understand is why you say that it is better to use strict comparision when comparing to "." and "..". The readdir() function will always return a string (or the false) so I don't see the point. I'd also like to add that cleaning up after yourself is indeed always a good idea, one would think that after return when the $handle variable goes out of scope, closedir() would happen automatically but I just wrote a little test program, and it doesn't. Which is strange because other stuff, like flock do happen automatically.

                                                              – soger
                                                              Nov 20 '18 at 17:49
















                                                            2














                                                            @ Your Common Sense



                                                            I think your performant example could be more performant using strict comparison:



                                                            function is_dir_empty($dir) {
                                                            if (!is_readable($dir)) return null;
                                                            $handle = opendir($dir);
                                                            while (false !== ($entry = readdir($handle))) {
                                                            if ($entry !== '.' && $entry !== '..') { // <-- better use strict comparison here
                                                            closedir($handle); // <-- always clean up! Close the directory stream
                                                            return false;
                                                            }
                                                            }
                                                            closedir($handle); // <-- always clean up! Close the directory stream
                                                            return true;
                                                            }





                                                            share|improve this answer





















                                                            • 1





                                                              Good point regarding clean up: The return false case is not taking care of it ;-)

                                                              – Beat Christen
                                                              Sep 27 '16 at 13:02











                                                            • @BeatChristen Thx for the hint! Fixed it.

                                                              – André Fiedler
                                                              Sep 28 '16 at 6:37











                                                            • What I don't understand is why you say that it is better to use strict comparision when comparing to "." and "..". The readdir() function will always return a string (or the false) so I don't see the point. I'd also like to add that cleaning up after yourself is indeed always a good idea, one would think that after return when the $handle variable goes out of scope, closedir() would happen automatically but I just wrote a little test program, and it doesn't. Which is strange because other stuff, like flock do happen automatically.

                                                              – soger
                                                              Nov 20 '18 at 17:49














                                                            2












                                                            2








                                                            2







                                                            @ Your Common Sense



                                                            I think your performant example could be more performant using strict comparison:



                                                            function is_dir_empty($dir) {
                                                            if (!is_readable($dir)) return null;
                                                            $handle = opendir($dir);
                                                            while (false !== ($entry = readdir($handle))) {
                                                            if ($entry !== '.' && $entry !== '..') { // <-- better use strict comparison here
                                                            closedir($handle); // <-- always clean up! Close the directory stream
                                                            return false;
                                                            }
                                                            }
                                                            closedir($handle); // <-- always clean up! Close the directory stream
                                                            return true;
                                                            }





                                                            share|improve this answer















                                                            @ Your Common Sense



                                                            I think your performant example could be more performant using strict comparison:



                                                            function is_dir_empty($dir) {
                                                            if (!is_readable($dir)) return null;
                                                            $handle = opendir($dir);
                                                            while (false !== ($entry = readdir($handle))) {
                                                            if ($entry !== '.' && $entry !== '..') { // <-- better use strict comparison here
                                                            closedir($handle); // <-- always clean up! Close the directory stream
                                                            return false;
                                                            }
                                                            }
                                                            closedir($handle); // <-- always clean up! Close the directory stream
                                                            return true;
                                                            }






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Sep 28 '16 at 6:37

























                                                            answered Aug 30 '13 at 8:11









                                                            André FiedlerAndré Fiedler

                                                            69121022




                                                            69121022








                                                            • 1





                                                              Good point regarding clean up: The return false case is not taking care of it ;-)

                                                              – Beat Christen
                                                              Sep 27 '16 at 13:02











                                                            • @BeatChristen Thx for the hint! Fixed it.

                                                              – André Fiedler
                                                              Sep 28 '16 at 6:37











                                                            • What I don't understand is why you say that it is better to use strict comparision when comparing to "." and "..". The readdir() function will always return a string (or the false) so I don't see the point. I'd also like to add that cleaning up after yourself is indeed always a good idea, one would think that after return when the $handle variable goes out of scope, closedir() would happen automatically but I just wrote a little test program, and it doesn't. Which is strange because other stuff, like flock do happen automatically.

                                                              – soger
                                                              Nov 20 '18 at 17:49














                                                            • 1





                                                              Good point regarding clean up: The return false case is not taking care of it ;-)

                                                              – Beat Christen
                                                              Sep 27 '16 at 13:02











                                                            • @BeatChristen Thx for the hint! Fixed it.

                                                              – André Fiedler
                                                              Sep 28 '16 at 6:37











                                                            • What I don't understand is why you say that it is better to use strict comparision when comparing to "." and "..". The readdir() function will always return a string (or the false) so I don't see the point. I'd also like to add that cleaning up after yourself is indeed always a good idea, one would think that after return when the $handle variable goes out of scope, closedir() would happen automatically but I just wrote a little test program, and it doesn't. Which is strange because other stuff, like flock do happen automatically.

                                                              – soger
                                                              Nov 20 '18 at 17:49








                                                            1




                                                            1





                                                            Good point regarding clean up: The return false case is not taking care of it ;-)

                                                            – Beat Christen
                                                            Sep 27 '16 at 13:02





                                                            Good point regarding clean up: The return false case is not taking care of it ;-)

                                                            – Beat Christen
                                                            Sep 27 '16 at 13:02













                                                            @BeatChristen Thx for the hint! Fixed it.

                                                            – André Fiedler
                                                            Sep 28 '16 at 6:37





                                                            @BeatChristen Thx for the hint! Fixed it.

                                                            – André Fiedler
                                                            Sep 28 '16 at 6:37













                                                            What I don't understand is why you say that it is better to use strict comparision when comparing to "." and "..". The readdir() function will always return a string (or the false) so I don't see the point. I'd also like to add that cleaning up after yourself is indeed always a good idea, one would think that after return when the $handle variable goes out of scope, closedir() would happen automatically but I just wrote a little test program, and it doesn't. Which is strange because other stuff, like flock do happen automatically.

                                                            – soger
                                                            Nov 20 '18 at 17:49





                                                            What I don't understand is why you say that it is better to use strict comparision when comparing to "." and "..". The readdir() function will always return a string (or the false) so I don't see the point. I'd also like to add that cleaning up after yourself is indeed always a good idea, one would think that after return when the $handle variable goes out of scope, closedir() would happen automatically but I just wrote a little test program, and it doesn't. Which is strange because other stuff, like flock do happen automatically.

                                                            – soger
                                                            Nov 20 '18 at 17:49











                                                            0














                                                            I use this method in my Wordpress CSV 2 POST plugin.



                                                                public function does_folder_contain_file_type( $path, $extension ){
                                                            $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

                                                            $html_files = new RegexIterator( $all_files, '/.'.$extension.'/' );

                                                            foreach( $html_files as $file) {
                                                            return true;// a file with $extension was found
                                                            }

                                                            return false;// no files with our extension found
                                                            }


                                                            It works by specific extension but is easily changed to suit your needs by removing "new RegexIterator(" line. Count $all_files.



                                                                public function does_folder_contain_file_type( $path, $extension ){
                                                            $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

                                                            return count( $all_files );
                                                            }





                                                            share|improve this answer




























                                                              0














                                                              I use this method in my Wordpress CSV 2 POST plugin.



                                                                  public function does_folder_contain_file_type( $path, $extension ){
                                                              $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

                                                              $html_files = new RegexIterator( $all_files, '/.'.$extension.'/' );

                                                              foreach( $html_files as $file) {
                                                              return true;// a file with $extension was found
                                                              }

                                                              return false;// no files with our extension found
                                                              }


                                                              It works by specific extension but is easily changed to suit your needs by removing "new RegexIterator(" line. Count $all_files.



                                                                  public function does_folder_contain_file_type( $path, $extension ){
                                                              $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

                                                              return count( $all_files );
                                                              }





                                                              share|improve this answer


























                                                                0












                                                                0








                                                                0







                                                                I use this method in my Wordpress CSV 2 POST plugin.



                                                                    public function does_folder_contain_file_type( $path, $extension ){
                                                                $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

                                                                $html_files = new RegexIterator( $all_files, '/.'.$extension.'/' );

                                                                foreach( $html_files as $file) {
                                                                return true;// a file with $extension was found
                                                                }

                                                                return false;// no files with our extension found
                                                                }


                                                                It works by specific extension but is easily changed to suit your needs by removing "new RegexIterator(" line. Count $all_files.



                                                                    public function does_folder_contain_file_type( $path, $extension ){
                                                                $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

                                                                return count( $all_files );
                                                                }





                                                                share|improve this answer













                                                                I use this method in my Wordpress CSV 2 POST plugin.



                                                                    public function does_folder_contain_file_type( $path, $extension ){
                                                                $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

                                                                $html_files = new RegexIterator( $all_files, '/.'.$extension.'/' );

                                                                foreach( $html_files as $file) {
                                                                return true;// a file with $extension was found
                                                                }

                                                                return false;// no files with our extension found
                                                                }


                                                                It works by specific extension but is easily changed to suit your needs by removing "new RegexIterator(" line. Count $all_files.



                                                                    public function does_folder_contain_file_type( $path, $extension ){
                                                                $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

                                                                return count( $all_files );
                                                                }






                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Aug 1 '14 at 16:37









                                                                Ryan BayneRyan Bayne

                                                                1449




                                                                1449























                                                                    0














                                                                    I had a similar problem recently, although, the highest up-voted answer did not really work for me, hence, I had to come up with a similar solution. and again this may also not be the most efficient way to go about the problem,



                                                                    I created a function like so



                                                                    function is_empty_dir($dir)
                                                                    {
                                                                    if (is_dir($dir))
                                                                    {
                                                                    $objects = scandir($dir);
                                                                    foreach ($objects as $object)
                                                                    {
                                                                    if ($object != "." && $object != "..")
                                                                    {
                                                                    if (filetype($dir."/".$object) == "dir")
                                                                    {
                                                                    return false;
                                                                    } else {
                                                                    return false;
                                                                    }
                                                                    }
                                                                    }
                                                                    reset($objects);
                                                                    return true;
                                                                    }


                                                                    and used it to check for empty dricetory like so



                                                                    if(is_empty_dir($path)){
                                                                    rmdir($path);
                                                                    }





                                                                    share|improve this answer




























                                                                      0














                                                                      I had a similar problem recently, although, the highest up-voted answer did not really work for me, hence, I had to come up with a similar solution. and again this may also not be the most efficient way to go about the problem,



                                                                      I created a function like so



                                                                      function is_empty_dir($dir)
                                                                      {
                                                                      if (is_dir($dir))
                                                                      {
                                                                      $objects = scandir($dir);
                                                                      foreach ($objects as $object)
                                                                      {
                                                                      if ($object != "." && $object != "..")
                                                                      {
                                                                      if (filetype($dir."/".$object) == "dir")
                                                                      {
                                                                      return false;
                                                                      } else {
                                                                      return false;
                                                                      }
                                                                      }
                                                                      }
                                                                      reset($objects);
                                                                      return true;
                                                                      }


                                                                      and used it to check for empty dricetory like so



                                                                      if(is_empty_dir($path)){
                                                                      rmdir($path);
                                                                      }





                                                                      share|improve this answer


























                                                                        0












                                                                        0








                                                                        0







                                                                        I had a similar problem recently, although, the highest up-voted answer did not really work for me, hence, I had to come up with a similar solution. and again this may also not be the most efficient way to go about the problem,



                                                                        I created a function like so



                                                                        function is_empty_dir($dir)
                                                                        {
                                                                        if (is_dir($dir))
                                                                        {
                                                                        $objects = scandir($dir);
                                                                        foreach ($objects as $object)
                                                                        {
                                                                        if ($object != "." && $object != "..")
                                                                        {
                                                                        if (filetype($dir."/".$object) == "dir")
                                                                        {
                                                                        return false;
                                                                        } else {
                                                                        return false;
                                                                        }
                                                                        }
                                                                        }
                                                                        reset($objects);
                                                                        return true;
                                                                        }


                                                                        and used it to check for empty dricetory like so



                                                                        if(is_empty_dir($path)){
                                                                        rmdir($path);
                                                                        }





                                                                        share|improve this answer













                                                                        I had a similar problem recently, although, the highest up-voted answer did not really work for me, hence, I had to come up with a similar solution. and again this may also not be the most efficient way to go about the problem,



                                                                        I created a function like so



                                                                        function is_empty_dir($dir)
                                                                        {
                                                                        if (is_dir($dir))
                                                                        {
                                                                        $objects = scandir($dir);
                                                                        foreach ($objects as $object)
                                                                        {
                                                                        if ($object != "." && $object != "..")
                                                                        {
                                                                        if (filetype($dir."/".$object) == "dir")
                                                                        {
                                                                        return false;
                                                                        } else {
                                                                        return false;
                                                                        }
                                                                        }
                                                                        }
                                                                        reset($objects);
                                                                        return true;
                                                                        }


                                                                        and used it to check for empty dricetory like so



                                                                        if(is_empty_dir($path)){
                                                                        rmdir($path);
                                                                        }






                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Aug 8 '15 at 11:22









                                                                        user28864user28864

                                                                        1,9591817




                                                                        1,9591817























                                                                            0














                                                                            You can use this:



                                                                            function isEmptyDir($dir)
                                                                            {
                                                                            return (($files = @scandir($dir)) && count($files) <= 2);
                                                                            }





                                                                            share|improve this answer




























                                                                              0














                                                                              You can use this:



                                                                              function isEmptyDir($dir)
                                                                              {
                                                                              return (($files = @scandir($dir)) && count($files) <= 2);
                                                                              }





                                                                              share|improve this answer


























                                                                                0












                                                                                0








                                                                                0







                                                                                You can use this:



                                                                                function isEmptyDir($dir)
                                                                                {
                                                                                return (($files = @scandir($dir)) && count($files) <= 2);
                                                                                }





                                                                                share|improve this answer













                                                                                You can use this:



                                                                                function isEmptyDir($dir)
                                                                                {
                                                                                return (($files = @scandir($dir)) && count($files) <= 2);
                                                                                }






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Mar 6 '17 at 19:29









                                                                                karrtojalkarrtojal

                                                                                35138




                                                                                35138























                                                                                    0














                                                                                    The first question is when is a directory empty? In a directory there are 2 files the '.' and '..'.

                                                                                    Next to that on a Mac there maybe the file '.DS_Store'. This file is created when some kind of content is added to the directory. If these 3 files are in the directory you may say the directory is empty.
                                                                                    So to test if a directory is empty (without testing if $dir is a directory):



                                                                                    function isDirEmpty( $dir ) {
                                                                                    $count = 0;
                                                                                    foreach (new DirectoryIterator( $dir ) as $fileInfo) {
                                                                                    if ( $fileInfo->isDot() || $fileInfo->getBasename() == '.DS_Store' ) {
                                                                                    continue;
                                                                                    }
                                                                                    $count++;
                                                                                    }
                                                                                    return ($count === 0);
                                                                                    }





                                                                                    share|improve this answer




























                                                                                      0














                                                                                      The first question is when is a directory empty? In a directory there are 2 files the '.' and '..'.

                                                                                      Next to that on a Mac there maybe the file '.DS_Store'. This file is created when some kind of content is added to the directory. If these 3 files are in the directory you may say the directory is empty.
                                                                                      So to test if a directory is empty (without testing if $dir is a directory):



                                                                                      function isDirEmpty( $dir ) {
                                                                                      $count = 0;
                                                                                      foreach (new DirectoryIterator( $dir ) as $fileInfo) {
                                                                                      if ( $fileInfo->isDot() || $fileInfo->getBasename() == '.DS_Store' ) {
                                                                                      continue;
                                                                                      }
                                                                                      $count++;
                                                                                      }
                                                                                      return ($count === 0);
                                                                                      }





                                                                                      share|improve this answer


























                                                                                        0












                                                                                        0








                                                                                        0







                                                                                        The first question is when is a directory empty? In a directory there are 2 files the '.' and '..'.

                                                                                        Next to that on a Mac there maybe the file '.DS_Store'. This file is created when some kind of content is added to the directory. If these 3 files are in the directory you may say the directory is empty.
                                                                                        So to test if a directory is empty (without testing if $dir is a directory):



                                                                                        function isDirEmpty( $dir ) {
                                                                                        $count = 0;
                                                                                        foreach (new DirectoryIterator( $dir ) as $fileInfo) {
                                                                                        if ( $fileInfo->isDot() || $fileInfo->getBasename() == '.DS_Store' ) {
                                                                                        continue;
                                                                                        }
                                                                                        $count++;
                                                                                        }
                                                                                        return ($count === 0);
                                                                                        }





                                                                                        share|improve this answer













                                                                                        The first question is when is a directory empty? In a directory there are 2 files the '.' and '..'.

                                                                                        Next to that on a Mac there maybe the file '.DS_Store'. This file is created when some kind of content is added to the directory. If these 3 files are in the directory you may say the directory is empty.
                                                                                        So to test if a directory is empty (without testing if $dir is a directory):



                                                                                        function isDirEmpty( $dir ) {
                                                                                        $count = 0;
                                                                                        foreach (new DirectoryIterator( $dir ) as $fileInfo) {
                                                                                        if ( $fileInfo->isDot() || $fileInfo->getBasename() == '.DS_Store' ) {
                                                                                        continue;
                                                                                        }
                                                                                        $count++;
                                                                                        }
                                                                                        return ($count === 0);
                                                                                        }






                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Jun 8 '18 at 17:13









                                                                                        HarmHarm

                                                                                        46369




                                                                                        46369






























                                                                                            draft saved

                                                                                            draft discarded




















































                                                                                            Thanks for contributing an answer to Stack Overflow!


                                                                                            • Please be sure to answer the question. Provide details and share your research!

                                                                                            But avoid



                                                                                            • Asking for help, clarification, or responding to other answers.

                                                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                                                            To learn more, see our tips on writing great answers.




                                                                                            draft saved


                                                                                            draft discarded














                                                                                            StackExchange.ready(
                                                                                            function () {
                                                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7497733%2fhow-can-i-use-php-to-check-if-a-directory-is-empty%23new-answer', 'question_page');
                                                                                            }
                                                                                            );

                                                                                            Post as a guest















                                                                                            Required, but never shown





















































                                                                                            Required, but never shown














                                                                                            Required, but never shown












                                                                                            Required, but never shown







                                                                                            Required, but never shown

































                                                                                            Required, but never shown














                                                                                            Required, but never shown












                                                                                            Required, but never shown







                                                                                            Required, but never shown







                                                                                            Popular posts from this blog

                                                                                            MongoDB - Not Authorized To Execute Command

                                                                                            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                                                                            How to fix TextFormField cause rebuild widget in Flutter