Check empty folder in PHP

Asked

Viewed 200 times

-3

I need to find out if a folder is empty or not using PHP, because I have an image registration system, only when I delete the images from the folder, it is still there.

My goal is whenever there are no more photos in the folder it is automatically deleted, I have researched about and found nothing to help me.

Fictitious example:

$ dir = 'pastaRaiz/dirTest';

if($dir == 'empty'){ 
  echo 'Diretório vazio deletado !';
  rmdir($dir)
}
  • Use rmdir($dir); Reference: https://www.php.net/manual/en/function.rmdir.php

  • 2

    If the directory usually contains few files, you can use the scandir. For directories with many files, better use the file system Iterators php.

  • I already got what I wanted using scandir() . Thanks for the help. <? php echo '<H1>Folder:</H1><br>'; $dir = './Test folder'; $files1 = scandir($dir); // $files2 = scandir($dir, 1); print_r($files1); echo "<br>"; echo $files1[3]; echo "<br>"; if(!$files1[3]){ rmdir($dir); echo 'Deleted folder ! '; }Else{ echo "<br>"; echo 'Content archive; } ?>

1 answer

1


Hello all right? The combination of functions count and glob PHP can help you in this task. For this you should perform the following check:

<?php

    $empty = ((count(glob("$dir/*")) === 0) ? true : false);

?>

Then, if the variable $empty is returning true, delete the desired folder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.