I have a website on a shared server and I want to check if a specific folder is empty. I tried out at least 5 ways. I am testing two folders. And empty one and one with a file.
$userid = '000019'; //000019 is empty, 000021 has one file
$server_dir = $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$dir = $server_dir . "/Trips/".$userid."/";
echo 'DIR: '.$dir; //www.example.com/Trips/000019/
FIRST
function checkFolderIsEmptyOrNot ( $folderName ){
$files = array ();
if ( $handle = opendir ( $folderName ) ) {
while ( false !== ( $file = readdir ( $handle ) ) ) {
if ( $file != "." && $file != ".." ) {
$files [] = $file;
}
}
closedir ( $handle );
}
return ( count ( $files ) > 0 ) ? TRUE: FALSE; }
if (checkFolderIsEmptyOrNot($dir)) {
echo 'X';
} else {
echo 'Y';
}
echo 'EMPTY?: '.checkFolderIsEmptyOrNot($dir); //always Y
SECOND
function dir_is_empty($path)
{
$empty = true;
$dir = opendir($path);
while($file = readdir($dir))
{
if($file != '.' && $file != '..')
{
$empty = false;
break;
}
}
closedir($dir);
return $empty;
}
echo 'EMPTY?: '.dir_is_empty($dir).'<br>'; //always 1
THIRD
function is_dir_empty($dir) {
if (!is_readable($dir)) return NULL;
return (count(scandir($dir)) == 2);
}
if (is_dir_empty($dir)) {
echo "the folder is empty";
}else{
echo "the folder is NOT empty"; //always NOT empty
}
And so on. What can be the problem? What am I missing here?
PHP version is 5.5
When I open www.example.com/Trips/000019/ in the browser it says I don't have access to this folder. Although I can access the file inside the folder, like www.example.com/Trips/000019/a.pdf
EDIT
With your help guys this is the glob code that says to all folder "not empty":
<?php
header('Content-type: text/html; charset=UTF-8');
session_start();
echo $_SESSION['userid'] = '000019';
$server_dir = $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
//$dir = $server_dir . "/Trips/".$userid."/";
$dir = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "Trips" . DIRECTORY_SEPARATOR . $_SESSION['userid'] . DIRECTORY_SEPARATOR;
echo 'DIR: '.$dir.'<br>';
$files = array();
if ($dh = opendir($dir)) {
while (false !== ($file = readdir($dh))) {
if ($file != "." && $file != "..") $files[] = $file;
}
}
print_r($files);
if (count(glob($dir)) === 0 ) {
echo "the folder is empty";
} else {
echo "the folder is NOT empty";
}
?>
Result:
000019
DIR: /home/myusername/public_html/Trips/000019/
Array ( ) the folder is NOT empty
As you see the Array is empty.