function countFiles($path='.', $extension='.pdf')
{
$pdfs = 0;
if(!is_dir($path))
{
return FALSE; // Not a real directory, fail
}
else
{
// Proper directory, now let's search:
$path = (substr($path, -1)=='/')?substr($path, 0, -1):$path; // remove trailing slash
$d = dir($path);
while( ($files = $d->read()) != FALSE)
{
if(!is_dir($path.'/'.$files) && ($files != '.' && $files != '..') && !is_link($path.'/'.$files))
{
// Not a directory, not "current" or "parent" directory links, not a symbolic link
if(strrchr($files, '.') == $extension)
{
// We've found a PDF file!!! whew!!
$pdfs++;
}
}
}
return $pdfs;
}
}
It's a little more drawn out, but does what you have, and adds a few more checks.
To optimize your code, I'd say that you use [man]strrchr/man instead of substr() since [man]strrchr[/man] will find the last occurance of a character in a string. So it essentially searches from the right for the character you specify. It then returns everything from that point on (giving you only the extension). It's a little faster than the substr() call.
Now, to call this for the current directory, just do:
$num_of_pdfs = countFiles();
If there are any PDFs in that directory, it will count them. If not, it will return 0. If it's not actually a directory, or can't get to the directory (like paths that require apache's mod_rewrite) then it will return false. Obviously to check that it returned something you'd do:
$num_of_pdfs = countFiles('.', '.pdf'); // equivalent to countFiles();
if($num_of_pdfs === FALSE) // Check type of var (bool) & value (FALSE)
// 0 is an integer, and won't cause this to go off
{
echo 'Sorry, the directory couldn\'t be searched';
}
else
{
echo $num_of_pdfs.' were found!!';
}