tags:

views:

54

answers:

4

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
+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
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
i think this only counts the top level folder
HollerTrain
@Hol It does. I'll edit the answer, if you want the subfolders.
Artefacto
Great answer, I've never used that object before... learned something new today. :-)
KyleFarris
@Artefacto, the new code seems to be showing the same amount of code as the single dir version.
HollerTrain
ah nm i spoke too soon. takes a while to load :) let me poke around with this TY SO MUCH
HollerTrain
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
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