Hi, here is my code so far:

<?php
//List files in chosen directory
	$dir = opendir("uploads");
	while ($entryName = readdir($dir))
	{
		$dirArray[] = $entryName;
	}
	closedir($dir);
	
	$indexCount = count($dirArray);
	echo "$indexCount files <br />";
	
	for($index=0; $index < $indexCount; $index++)
	{
		if ($dirArray[$index] != "." && $dirArray[$index] != "..")
		{
			$type = filetype($dirArray[$index]);
			if ($type == "dir")
			{
				echo "<img src='dir.png' />";
			}
			else
				{
					echo "<img src='file.png' />";
				}
			
			echo "<a href='".$dirArray[$index]."'>".$dirArray[$index]."</a> <br />";
			
		}
	}
?>

My problem is that I when the indexCount, counts all my files, I just want it to display how many files there are of a chosen extension.
Let's say I just want it to tell me how many files I have of .jpg or .jpg and .png

Can someone help me with this?


Help will be much appriciated.

Dani AI

Generated

A concise, practical summary and a few safe alternates to count only files with chosen extension(s).

For a quick one-folder solution, use shell-style filename matching (glob) and count the results. This is fast and simple:

$files = glob(__DIR__ . '/uploads/*.{jpg,jpeg,png}', GLOB_BRACE);
$count = count($files);

If case sensitivity or recursion is needed, filter the file list with a case-insensitive regex or use SPL iterators to avoid loading everything into an array:

$all = glob(__DIR__ . '/uploads/*.*');
$matches = preg_grep('/\.(jpe?g|png)$/i', $all);
$count = count($matches);

For recursive searches use a RecursiveDirectoryIterator wrapped in a RegexIterator to match extensions without building huge arrays:

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/uploads'));
$regex = new RegexIterator($it, '/\.(?:jpe?g|png)$/i', RegexIterator::MATCH);
$count = iterator_count($regex);

Notes, pitfalls and best practices:

  • ’s original loop will include “.” and “..” and may mis-report filetype if functions are given only the filename; pass the full path (e.g. $path.DIRECTORY_SEPARATOR.$file) to is_file()/filetype()/finfo.
  • ’s pathinfo approach and ’s header-check advice are both valid: extension checks are fastest; header checks (exif_imagetype or finfo) are more accurate but slower.
  • For large directories prefer iterator-based solutions (memory efficient).
  • Always escape output (htmlspecialchars) and url-encode links when printing filenames to avoid XSS and broken links.
  • If exact MIME type matters (security, upload validation), inspect file headers (finfo_open/finfo_file or exif_imagetype) rather than trusting extensions.
  • ’s SPL FilterIterator approach is a robust reusable option when building a production utility.

These options cover quick scripts through production-ready filters; pick glob for simplicity, iterators for scale, and header inspection for correctness.

Recommended Answers

All 3 Replies

use this code to validate extension:

echo pathinfo($dirArray[$index], PATHINFO_EXTENSION);

Filetype is't what u want.
check for gif file

if (exif_imagetype($dirArray[$index]) == IMAGETYPE_GIF)
                     $NumberOfGif++;

to check for other image types see
http://nl.php.net/manual/en/function.exif-imagetype.php
This look inside the file and is therefor slow but gifs u the true type of the image
a .png renamed .gif wil be recognised as png

to simply check the exstenion or check for non images (faster!)
use

$path_parts = pathinfo($dirArray[$index]);
if ( $path_parts['extension']=='gif')
               $NumberOfGif++;

I know this will probably be a more advanced response than what you are looking for but there are a lot of advantages to this kind of code in terms of re-usability. So I'm going to post this hoping it helps you as well as anyone else who needs to solve the same kind of problem.

<?php

/**
 * ExtensionFilterIterator Class
 * Used to filter a directory iterator by any number of extensions
 * 
 * @link http://www.php.net/manual/en/class.filteriterator.php
 */
class ExtensionFilterIterator extends FilterIterator
{
	/**
	 * Stores an array of extensions to filter on
	 * @var array
	 */
	protected $_extensions = array();
    
	
	/**
	 * Creates a class instance and sets extensions to filter on
	 * @param Iterator $iterator
	 * @param array|string $extension
	 */
	public function __construct( Iterator $iterator , $extension )
	{
		parent::__construct( $iterator );
		if( is_string( $extension ) ){
			$this->_extensions[] = $extension;
		}
		
		if( is_array( $extension ) ){
			$this->_extensions = $extension;
		}
    }
    
    /**
     * Implementation of abstract accept method
     * Determines if item is a file and also if the file has a valid extension
     * 
     *@see FilterIterator::accept()
     */
    public function accept()
    {
        $item = $this->getInnerIterator()->current();
		if( $item->isFile() && in_array( substr( $item->getFilename(), ( strrpos( $item->getFilename(), '.') + 1 ) ), $this->_extensions ) ){
			return true;
		}
        return false;
    }
}

Once you have the ExtensionFilterIterator defined in a file that you can include/require into your project its usage is simple.

//Defile the path to the image directory
$path = 'images/';

//Create a DirectoryIterator instance with the path and wrap that instance with
//an instance of the ExtensionFilterIterator
$iterator = new ExtensionFilterIterator( new DirectoryIterator( $path ), array( 'jpg', 'png', 'gif' ) );

//User iterator_count function to count the number of items that pass through the filter
//@link http://php.net/manual/en/function.iterator-count.php
echo iterator_count($iterator);

Whats nice about this is not only can you count it for your numbers, but you can also loop over it.

//Defile the path to the image directory
$path = 'images/';

//Create a DirectoryIterator instance with the path and wrap that instance with
//an instance of the ExtensionFilterIterator
$iterator = new ExtensionFilterIterator( new DirectoryIterator( $path ), array( 'jpg', 'png', 'gif' ) );

foreach( $iterator as $file ){
    echo $file->getFilename().PHP_EOL; //each file item is an instance of SplFileInfo
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.