Is it possible using PHP to parse through an entire directory to find number of lines of code in all the files in the dir so this value can be output to the screen - using PHP?
+1
A:
This wouldn't be particularly efficient, but you could load each file in the directory and count the number of lines:
$total_lines = 0;
chdir($directory);
foreach (glob("*") as $file)
{
if (is_file($file))
{
$total_lines += count(file($file));
}
}
You might want a more restrictive glob construct if the directory contains non-text files as well.
Daniel Vandersluis
2010-06-22 16:35:32
+4
A:
$dit = new DirectoryIterator(".");
$count = 0;
$dit->rewind();
while ($dit->valid()) {
if ($dit->isFile()) {
foreach (new SplFileObject($dit->current()) as $line) {
$count++;
}
}
$dit->next();
}
echo $count; //output line count
To include subdirectories:
$dit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("."));
$count = 0;
$dit->rewind();
while ($dit->valid()) {
if ($dit->isFile()) {
foreach (new SplFileObject($dit->current()) as $line) {
$count++;
}
}
$dit->next();
}
echo $count; //output line count
Artefacto
2010-06-22 16:36:32
nice this worked perfect! so i am to assume if i put this in a directory which has files in the directory AND folders in the directory that it will count the number of lines of code in the entire directory (files + folders in the parent dir this code sits in)?
HollerTrain
2010-06-22 17:06:39
i think this only counts the top level folder
HollerTrain
2010-06-22 17:20:19
@Hol It does. I'll edit the answer, if you want the subfolders.
Artefacto
2010-06-22 17:22:50
Great answer, I've never used that object before... learned something new today. :-)
KyleFarris
2010-06-22 17:27:39
@Artefacto, the new code seems to be showing the same amount of code as the single dir version.
HollerTrain
2010-06-22 17:41:20
ah nm i spoke too soon. takes a while to load :) let me poke around with this TY SO MUCH
HollerTrain
2010-06-22 17:45:25
A:
Yes it is possible.
By compining information from here and here you get:
<?php
if ($handle = opendir('.')) {
$count = 0;
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$lines = file($file);
$count += count($lines);
}
closedir($handle);
echo($count);
}
?>
Jacob Tomaw
2010-06-22 16:38:00
A:
If you don't have to use this on Windows, you could likely just use a shell command
echo (int) exec('wc -l filename.txt');
From the wc man page:
wc - print the number of newlines, words, and bytes in files
-l, --lines print the newline counts
Otherwise use Daniel's or Artefacto's approach.
Gordon
2010-06-22 16:45:32