Reply to Re: Command

Your name:

Reply:


Posted by Daniel Ennis on 01/14/08 00:32

Fred Atkinson wrote:
> On Sun, 13 Jan 2008 20:29:20 +0100, thib´ <thyb0@coralsnake-team.com>
> wrote:
>
>> Fred Atkinson wrote:
>>> I've looked at php.net and am not able to find this one.
>>>
>>> What is the function that will return the number of files in a
>>> subdirectory?
>>>
>>> Regards,
>>>
>>>
>>>
>>> Fred
>> Just try this one:
>> <?php
>> function countfiles($dir) {
>> if( $handle = opendir($dir) ) {
>> $c = 0;
>> while( $file = readdir($handle) )
>> if( !preg_match('/\.\.?/', $file) ) $c++;
>> return $c;
>> } else return false;
>> }
>> ?>
>>
>> This should make it; you can of course change de regexp filter or use
>> different methods (this one only avoids counting '.' and '..')
>>
>> Call example:
>>
>> Number of files in subdir 'dir/subdir/' is <?php echo
>> countfiles('dir/subdir/') or '[warning: unable to open dir]'; ?>
>>
>> -thib´
>
> I've tried this script. No matter how many files are in the
> directory, it says that there is only one file. The directory I used
> should have returned thirteen as a value.
>
> I tried making the path '.' so it would count the files in the
> same directory it was in. But it again said it there was only one
> when there was also thirteen files in that directory.
>
> Here is how I coded the call:
>
> <?php
> echo countfiles('.') or '[warning: unable to open dir]';
> ?>
>
> I copied it from your post. The only alterations I made were
> to make it three lines and change the directory location.
>
> Regards,
>
>
>
> Fred

Did you try my solution? It should be alot quicker than the above
method, but I did forget to ask, are their directories in the folder
that shouldnt be counted?

Thats a problem with the above example by thib also, file names without
extensions wouldnt be counted.

A sure fire way of doing it would be:

<?php
$dir = './directory';
function countfiles($dir = '.')
{
$count = 0;
$dir = rtrim($dir,'/').'/';
if(!is_dir($dir)) return false;
foreach(new DirectoryIterator($dir) as $file)
{
if(is_file($dir.$file)) $count++;
}
return $count;
}
echo countfiles();
?>

Of course, this is PHP5, and if you dont have PHP5, you should be
changing hosts :P Use these new SPL functions given to us for faster code!
--
Daniel Ennis
faNetworks.net - Quality Web Hosting and Ventrilo Services
System Administrator / Web Developer
PHP Developer for 6 years
daniel@fanetworks.net

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация