Languages :: PHP :: PHP counting files in a dir |
|||
| By: PHP newbee |
Date: 04/03/2003 00:00:00 |
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 | Type : Answer |
|
| no predefined function |
|||
| By: TheFalklands | Date: 04/03/2003 17:16:00 | 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 | Type : Comment |
|
| oopz error at line 2: countFiles(){ without that ; |
|||
| By: VGR | Date: 05/03/2003 07:27:00 | 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 | Type : Comment |
|
| yup |
|||
| By: VGR | Date: 05/03/2003 07:38:00 | 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 | 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 | 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 | Type : Comment |
|
| please share the points 8-) |
|||
|
Do register to be able to answer |
|||
©2010 These pages are served without commercial sponsorship. (No popup ads, etc...). Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE.
Please DO link to this page!








