visitor (0 QPoints)
  • FR
  • EN
  • NL
  • DE
  • ES
315 experts, 1193 registered users, 1659 questions already answered
European Experts Exchange, the very best site for high-quality IT solutions

New Improved Search!

 


05/10/2011 1h30 : Steve Jobs is dead, the father of Apple ][ is gone, we are all orphaned.

Languages :: PHP :: PHP counting files in a dir


By: PHP newbee U.S.A.  Date: 04/03/2003 00:00:00  English  Points: 25 Status: Answered
Quality : Excellent
Hi,

i am curious if anyone knows if PHP has a built in function that will read how many files are in a particular directory, and return that number.

I reailze the simplicity of this task but I am feeling particularly lazy today...

Thanks


By: VGR Date: 04/03/2003 08:41:00 English  Type : Answer
no predefined function
By: TheFalklands Date: 04/03/2003 17:16:00 English  Type : Assist
<?php
countFiles($dir){;
$cwd = getcwd();
chdir($dir);
$dh = opendir(".") or die("Could not open directory $dir");
$num = 0;

while($file = (readdir($dh) != false)){
if($file != "." && $file != ".." && is_file($file)){
$num++;
}
}//while

return $num;
}//countFiles()

print(countFiles("info"));
?>

that should do it =)
By: TheFalklands Date: 04/03/2003 17:17:00 English  Type : Comment
oopz error at line 2:
countFiles(){ without that ;
By: VGR Date: 05/03/2003 07:27:00 English  Type : Comment
you forgot what you apparently planned :
at the end before the return $num :
chdir($cwd); // to go back where we were
By: TheFalklands Date: 05/03/2003 07:30:00 English  Type : Comment
yup

By: VGR Date: 05/03/2003 07:38:00 English  Type : Comment
ah, and your style is "C-like" :D
Also, testing is_file($file) is enough to get rid of '.' and '..', no ??? :D :D :D
By: TheFalklands Date: 05/03/2003 07:41:00 English  Type : Comment
:D

gotta be sure!
Some systems may say that dirs are files..
depends on configuration.
By: PHP newbee Date: 05/03/2003 08:29:00 English  Type : Comment
Here is what I ended up doing...

if(is_dir("images/".$listing_id))
{
$num_files = 0;
clearstatcache();
$dir = opendir("images/".$listing_id);
while($file = readdir($dir))
{
if(($file != ".") && ($file != "..") && (is_file($file))
{
$num_files++;
}
}
}

This works great... I was having problems at first and I didn't know where the . and .. were coming from. After some trial and error I figured it out.

But since VGR was the first person to answer the original question for the post "does php have a built in function for this task"
He gets the points.
By: VGR Date: 05/03/2003 09:21:00 English  Type : Comment
please share the points 8-)

Do register to be able to answer

EContact
browser fav
page generated in 360.067840 milliseconds

Why Google AdSense ads ?

compteur
 Ranking-Hits PageRank for this page