Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

directory

php

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"; ?> 
like image 312
TheBlackBenzKid Avatar asked Sep 21 '11 09:09

TheBlackBenzKid


People also ask

How can I tell if a directory is empty?

To check whether a directory is empty or not os. listdir() method is used. os. listdir() method of os module is used to get the list of all the files and directories in the specified directory.

How do I view a directory in PHP?

PHP using scandir() to find folders in a directory To check if a folder or a file is in use, the function is_dir() or is_file() can be used. The scandir function is an inbuilt function that returns an array of files and directories of a specific directory.

How do you check if a folder contains a file in PHP?

The file_exists() function checks whether a file or directory exists. Note: The result of this function is cached.

Is PHP file empty?

PHP empty() FunctionThe empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.


1 Answers

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

like image 191
Your Common Sense Avatar answered Sep 23 '22 01:09

Your Common Sense