Jump to content

[SOLVED] How do I check if a directory is empty?


lpxxfaintxx

Recommended Posts

I wrote a simple piece that scans the directory for images only. How would I check if there are NO IMAGES in the folder? (Note, I said no images, not files). I want to make an if statement so that if no images exist in the folder, then echo 'whatever.'

 

Thanks

Gah! SO sorry, I meant to paste the code in the original post, but I must've forgot.

 




$featured_dir = 'albums/'.$random.'/original/'; 

$file_types = array('gif','jpg','png');


            $dir = 'albums/'.$random.'/';  
       $scan = scandir($dir);  

            for ($i=0; $i<count($scan); $i++) {  
             if ($scan[$i] != '.' && $scan[$i] != '..' && in_array(end(explode('.', $scan[$i])), $file_types)) {  
            echo ' 
              <p class="photoind">
		  
		  <a href="' . $featured_dir . $scan[$i] . '" rel="lightbox-'.$random.'"> 
            <img src="'. $dir . $scan[$i] . '" alt="'. $scan[$i] . '" width="132" height="132" rel="lightbox"/>

		  <br />       
		  </a> 
              </p>';  
              }    
             }  

<?php
$file_types = array('gif','jpg','png');

$dir = 'albums/'.$random.'/'; 
$scan = scandir($dir); 
$image_found = FALSE;

for ($i=0; $i<count($scan); $i++) { 
if ($scan[$i] != '.' && $scan[$i] != '..' && in_array(end(explode('.', $scan[$i])), $file_types)) { 
	$image_found = TRUE;
	echo '
	<p class="photoind">

	<a href="' . $featured_dir . $scan[$i] . '" rel="lightbox-'.$random.'">
	<img src="'. $dir . $scan[$i] . '" alt="'. $scan[$i] . '" width="132" height="132" rel="lightbox"/>

	<br />       
	</a>
	</p>'; 
} 
}  

if(!$image_found) {
//no image in directory
}

I'd suggest using glob() instead of scandir(). Then you can return all the image files and nothing else from the directory without a loop. And if the results are empty - then there are no images.

 

Give this a try

$images = glob('{*.jpg,*.gif,*.png}', GLOB_BRACE);

I would use a image function to do the check...

 


<?php

$out = 0;

$dir = './images';

$files = glob ( $dir . '/*' );

foreach ( $files AS $file )
{
if ( ! is_dir ( $file ) )
{
	if ( false !== @getimagesize ( $file ) )
	{
		$out++;
	}
}
}

if ( $out == 0 )
{
echo 'no images in directory: ' . $dir;
}
else
{
echo '(' . $out . ') total images found in directory: ' . $dir;
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.