Recursive File Search (PHP) - php

I'm trying to return the files in a specified directory using a recursive search.
I successfully achieved this, however I want to add a few lines of code that will allow me to specify certain extensions that I want to be returned.
For example return only .jpg files in the directory.
Here's my code,
<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
foreach(new RecursiveIteratorIterator($it) as $file) {
echo $file . "<br/> \n";
}
?>
please let me know what I can add to the above code to achieve this, thanks

<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
$display = Array ( 'jpeg', 'jpg' );
foreach(new RecursiveIteratorIterator($it) as $file)
{
if (in_array(strtolower(array_pop(explode('.', $file))), $display))
echo $file . "<br/> \n";
}
?>

You should create a filter:
class JpegOnlyFilter extends RecursiveFilterIterator
{
public function __construct($iterator)
{
parent::__construct($iterator);
}
public function accept()
{
return $this->current()->isFile() && preg_match("/\.jpe?g$/ui", $this->getFilename());
}
public function __toString()
{
return $this->current()->getFilename();
}
}
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
$it = new JpegOnlyFilter($it);
$it = new RecursiveIteratorIterator($it);
foreach ($it as $file)
...

Try this, it uses an array of allowed file types and only echos out the file if the file extension exists within the array.
<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
$allowed=array("pdf","txt");
foreach(new RecursiveIteratorIterator($it) as $file) {
if(in_array(substr($file, strrpos($file, '.') + 1),$allowed)) {
echo $file . "<br/> \n";
}
}
?>
You may also find that you could pass an array of allowed file types to your RecursiveDirectoryIterator class and only return files that match.

Let PHP do the job:
$directory = new RecursiveDirectoryIterator('path/to/directory/');
$iterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($iterator, '/\.jpe?g$/i', RecursiveRegexIterator::GET_MATCH);
echo '<pre>';
print_r($regex);

Regarding the top voted answer: I created this code which is using fewer functions, only 3, isset(), array_flip(), explode() instead of 4 functions. I tested the top voted answer and it was slower than mine. I suggest giving mine a try:
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
foreach(new RecursiveIteratorIterator($it) as $file) {
$FILE = array_flip(explode('.', $file));
if (isset($FILE['php']) || isset($FILE['jpg'])) {
echo $file. "<br />";
}
}

None of these worked for my case. So i wrote this function, not sure about efficiency, I just wanted to remove some duplicate photos quickly. Hope it helps someone else.
function rglob($dir, $pattern, $matches=array())
{
$dir_list = glob($dir . '*/');
$pattern_match = glob($dir . $pattern);
$matches = array_merge($matches, $pattern_match);
foreach($dir_list as $directory)
{
$matches = rglob($directory, $pattern, $matches);
}
return $matches;
}
$matches = rglob("C:/Bridge/", '*(2).ARW');
Only slight improvement that could be made is that currently for it to work you have to have a trailing forward slash on the start directory.

In this sample code;
You can set any path for $directory variable, for example ./, 'L:\folder\folder\folder' or anythings...
And also you can set a pattern file name in $pattern optional, You can put '/\.jpg$/' for every file with .jpg extension, and also if you want to find all files, can just use '//' for this variable.
$directory = 'L:\folder\folder\folder';
$pattern = '/\.jpg$/'; //use "//" for all files
$directoryIterator = new RecursiveDirectoryIterator($directory);
$iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
$regexIterator = new RegexIterator($iteratorIterator, $pattern);
foreach ($regexIterator as $file) {
if (is_dir($file)) continue;
echo "$file\n";
}

here is the correct way to search in folders and sub folders
$it = new RecursiveDirectoryIterator(__DIR__);
$findExts = Array ( 'jpeg', 'jpg' );
foreach(new RecursiveIteratorIterator($it) as $file)
{
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext, $findExts)){
echo $file.PHP_EOL;
}
}

You might want to check out this page about using glob() for a similar search:
http://www.electrictoolbox.com/php-glob-find-files/

Related

php glob - scan in subfolders for a file

I have a server with a lot of files inside various folders, sub-folders, and sub-sub-folders.
I'm trying to make a search.php page that would be used to search the whole server for a specific file. If the file is found, then return the location path to display a download link.
Here's what i have so far:
$root = $_SERVER['DOCUMENT_ROOT'];
$search = "test.zip";
$found_files = glob("$root/*/test.zip");
$downloadlink = str_replace("$root/", "", $found_files[0]);
if (!empty($downloadlink)) {
echo "$search";
}
The script is working perfectly if the file is inside the root of my domain name... Now i'm trying to find a way to make it also scan sub-folders and sub-sub-folders but i'm stuck here.
There are 2 ways.
Use glob to do recursive search:
<?php
// Does not support flag GLOB_BRACE
function rglob($pattern, $flags = 0) {
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$files = array_merge(
[],
...[$files, rglob($dir . "/" . basename($pattern), $flags)]
);
}
return $files;
}
// usage: to find the test.zip file recursively
$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/test.zip');
var_dump($result);
// to find the all files that names ends with test.zip
$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/*test.zip');
?>
Use RecursiveDirectoryIterator
<?php
// $regPattern should be using regular expression
function rsearch($folder, $regPattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $regPattern, RegexIterator::GET_MATCH);
$fileList = array();
foreach($files as $file) {
$fileList = array_merge($fileList, $file);
}
return $fileList;
}
// usage: to find the test.zip file recursively
$result = rsearch($_SERVER['DOCUMENT_ROOT'], '/.*\/test\.zip/'));
var_dump($result);
?>
RecursiveDirectoryIterator comes with PHP5 while glob is from PHP4. Both can do the job, it's up to you.
I want to provide another simple alternative for cases where you can predict a max depth. You can use a pattern with braces listing all possible subfolder depths.
This example allows 0-3 arbitrary subfolders:
glob("$root/{,*/,*/*/,*/*/*/}test_*.zip", GLOB_BRACE);
Of course the braced pattern could be procedurally generated.
This returns fullpath to the file
function rsearch($folder, $pattern) {
$iti = new RecursiveDirectoryIterator($folder);
foreach(new RecursiveIteratorIterator($iti) as $file){
if(strpos($file , $pattern) !== false){
return $file;
}
}
return false;
}
call the function:
$filepath = rsearch('/home/directory/thisdir/', "/findthisfile.jpg");
And this is returns like:
/home/directory/thisdir/subdir/findthisfile.jpg
You can improve this function to find several files like all jpeg file:
function rsearch($folder, $pattern_array) {
$return = array();
$iti = new RecursiveDirectoryIterator($folder);
foreach(new RecursiveIteratorIterator($iti) as $file){
if (in_array(strtolower(array_pop(explode('.', $file))), $pattern_array)){
$return[] = $file;
}
}
return $return;
}
This can call as:
$filepaths = rsearch('/home/directory/thisdir/', array('jpeg', 'jpg') );
Ref: https://stackoverflow.com/a/1860417/219112
As a full solution for your problem (this was also my problem):
<?php
function rsearch($folder, $pattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $pattern, RegexIterator::MATCH);
foreach($files as $file) {
yield $file->getPathName();
}
}
Will get you the full path of the items that you wish to find.
Edit: Thanks to Rousseau Alexandre for pointing out , $pattern must be regular expression.

Directory iterator and recursive directory iterator

I had to list all files and folders in a directory:
$images = array();
$dirs = array();
$dir = new DirectoryIterator($upload_dir_real);
foreach ($dir as $file) {
if ($file->isDot()) {
continue;
}
if ($file->isDir()) {
// dir
$scanned_dirs[] = $file->getPath();
continue;
} else {
// file
//echo $file->getFilename() . "<br>\n";//DEBUG
$realfile = $file->getFilename() . "<br>\n";
$realpath = $file->getPathname();
echo realpath($realfile);//DEBUG
$file->getFilename();
$images[] = realpath( $realpath );
}
}
This works fine (no errors) but of course counted only the root, so I tried recursive:
$images = array();
$dirs = array();
$dir = new RecursiveDirectoryIterator($upload_dir_real);
foreach ($dir as $file) {
if ($file->isDot()) {
continue;
}
if ($file->isDir()) {
// dir
$scanned_dirs[] = $file->getsubPath();
continue;
} else {
// file
//echo $file->getFilename() . "<br>\n"; //DEBUG
$realfile = $file->getsubFilename() . "<br>\n";
$realpath = $file->getsubPathname();
echo realpath($realfile);//DEBUG
$file->getFilename();
$images[] = realpath( $realpath );
}
}
Basically, I changed the getPath(); with getsubPath() (and equivalent). The problem is that it give me an error:
Fatal error: Call to undefined method SplFileInfo::isDot() in blah blah path
so I searched a while and found this:
Why does isDot() fail on me? (PHP)
This is basically the same problem, but when I try, I get this error:
Fatal error: Class 'FilesystemIterator' not found in in blah blah path
Questions:
1 - why is the method described in the other accepted answer not working for me?
2 - in that same answer, what is the following code:
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$pathToFolder,
FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_SELF));
This actually calls RecursiveIteratorIterator twice? I mean, if it is recursive, it can not be recursive twice :-)
2b - how come FilesystemIterator is not found, even if the PHP manual states (to my understanding) that it is a part of what the recursive iterator is built upon?
(Those questions are because I want to understand better, not to just copy and paste answers).
3 - is there a better way to list all folders and files cross platform?
1 - why is the method described in the other accepted answer not working for me ??`
As far as i can tell . the code works perfectly but your implementation is wrong you are using the following
Code
$dir = new RecursiveDirectoryIterator($upload_dir_real);
Instead of
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($upload_dir_real));
In that same answer actually calls RecursiveIteratorIterator twice ?? I mean, if it is recursive , it can not be recursive twice ... :-))
No it does not its different
RecursiveIteratorIterator != RecursiveDirectoryIterator != FilesystemIterator
^ ^
how come FilesystemIterator is not found , even if the php manual states (to my understanding) that it is a part of what the recursive iterator is built upon??
You already answered that your self in your comment you are using PHP version 5.2.9 which is no longer supported or recommended
3 - Is there a better way to list all folder and files cross platform ??
Since that is resolved all you need is FilesystemIterator::SKIP_DOTS you don't have to call $file->isDot()
Example
$fullPath = __DIR__;
$dirs = $files = array();
$directory = new RecursiveDirectoryIterator($fullPath, FilesystemIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST) as $path ) {
$path->isDir() ? $dirs[] = $path->__toString() : $files[] = realpath($path->__toString());
}
var_dump($files, $dirs);
Here is another method, utilizing setFlags:
<?php
$o_dir = new RecursiveDirectoryIterator('.');
$o_dir->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$o_iter = new RecursiveIteratorIterator($o_dir);
foreach ($o_iter as $o_info) {
echo $o_info->getPathname(), "\n";
}
https://php.net/filesystemiterator.setflags

Exclude hidden files from scandir

I am using the following code to get a list of images in a directory:
$files = scandir($imagepath);
but $files also includes hidden files. How can I exclude them?
On Unix, you can use preg_grep to filter out filenames that start with a dot:
$files = preg_grep('/^([^.])/', scandir($imagepath));
I tend to use DirectoryIterator for things like this which provides a simple method for ignoring dot files:
$path = '/your/path';
foreach (new DirectoryIterator($path) as $fileInfo) {
if($fileInfo->isDot()) continue;
$file = $path.$fileInfo->getFilename();
}
$files = array_diff(scandir($imagepath), array('..', '.'));
or
$files = array_slice(scandir($imagepath), 2);
might be faster than
$files = preg_grep('/^([^.])/', scandir($imagepath));
function nothidden($path) {
$files = scandir($path);
foreach($files as $file) {
if ($file[0] != '.') $nothidden[] = $file;
return $nothidden;
}
}
Simply use this function
$files = nothidden($imagepath);
I encountered a comment from php.net, specifically for Windows systems: http://php.net/manual/en/function.filetype.php#87161
Quoting here for archive purposes:
I use the CLI version of PHP on Windows Vista. Here's how to determine if a file is marked "hidden" by NTFS:
function is_hidden_file($fn) {
$attr = trim(exec('FOR %A IN ("'.$fn.'") DO #ECHO %~aA'));
if($attr[3] === 'h')
return true;
return false;
}
Changing if($attr[3] === 'h') to if($attr[4] === 's') will check for system files.
This should work on any Windows OS that provides DOS shell commands.
I reckon because you are trying to 'filter' out the hidden files, it makes more sense and looks best to do this...
$items = array_filter(scandir($directory), function ($item) {
return 0 !== strpos($item, '.');
});
I'd also not call the variable $files as it implies that it only contains files, but you could in fact get directories as well...in some instances :)
use preg_grep to exclude files name with special characters for e.g.
$dir = "images/";
$files = preg_grep('/^([^.])/', scandir($dir));
http://php.net/manual/en/function.preg-grep.php
Assuming the hidden files start with a . you can do something like this when outputting:
foreach($files as $file) {
if(strpos($file, '.') !== (int) 0) {
echo $file;
}
}
Now you check for every item if there is no . as the first character, and if not it echos you like you would do.
Use the following code if you like to reset the array index too and set the order:
$path = "the/path";
$files = array_values(
preg_grep(
'/^([^.])/',
scandir($path, SCANDIR_SORT_ASCENDING)
));
One line:
$path = "daten/kundenimporte/";
$files = array_values(preg_grep('/^([^.])/', scandir($path, SCANDIR_SORT_ASCENDING)));
scandir() is a built-in function, which by default select hidden file as well,
if your directory has only . & .. hidden files then try selecting files
$files = array_diff(scandir("path/of/dir"),array(".","..")) //can add other hidden file if don't want to consider
I am still leaving the checkmark for seengee's solution and I would have posted a comment below for a slight correction to his solution.
His solution masks the directories(. and ..) but does not mask hidden files like .htaccess
A minor tweak solves the problem:
foreach(new DirectoryIterator($curDir) as $fileInfo) {
//Check for something like .htaccess in addition to . and ..
$fileName = $fileInfo->getFileName();
if(strlen(strstr($fileName, '.', true)) < 1) continue;
echo "<h3>" . $fileName . "</h3>";
}

Deleting all files from a folder using PHP?

For example I had a folder called `Temp' and I wanted to delete or flush all files from this folder using PHP. Could I do this?
$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove 'hidden' files like .htaccess, you have to use
$files = glob('path/to/temp/{,.}*', GLOB_BRACE);
If you want to delete everything from folder (including subfolders) use this combination of array_map, unlink and glob:
array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );
This call can also handle empty directories ( thanks for the tip, #mojuba!)
Here is a more modern approach using the Standard PHP Library (SPL).
$dir = "path/to/directory";
if(file_exists($dir)){
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
$file->isDir() ? rmdir($file) : unlink($file);
}
}
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
if(!$fileInfo->isDot()) {
unlink($fileInfo->getPathname());
}
}
This code from http://php.net/unlink:
/**
* Delete a file or recursively delete a directory
*
* #param string $str Path to file or directory
*/
function recursiveDelete($str) {
if (is_file($str)) {
return #unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
recursiveDelete($path);
}
return #rmdir($str);
}
}
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}
Assuming you have a folder with A LOT of files reading them all and then deleting in two steps is not that performing.
I believe the most performing way to delete files is to just use a system command.
For example on linux I use :
exec('rm -f '. $absolutePathToFolder .'*');
Or this if you want recursive deletion without the need to write a recursive function
exec('rm -f -r '. $absolutePathToFolder .'*');
the same exact commands exists for any OS supported by PHP.
Keep in mind this is a PERFORMING way of deleting files. $absolutePathToFolder MUST be checked and secured before running this code and permissions must be granted.
See readdir and unlink.
<?php
if ($handle = opendir('/path/to/files'))
{
echo "Directory handle: $handle\n";
echo "Files:\n";
while (false !== ($file = readdir($handle)))
{
if( is_file($file) )
{
unlink($file);
}
}
closedir($handle);
}
?>
The simple and best way to delete all files from a folder in PHP
$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
if(is_file($file))
unlink($file); //delete file
}
Got this source code from here - http://www.codexworld.com/delete-all-files-from-folder-using-php/
unlinkr function recursively deletes all the folders and files in given path by making sure it doesn't delete the script itself.
function unlinkr($dir, $pattern = "*") {
// find all files and folders matching pattern
$files = glob($dir . "/$pattern");
//interate thorugh the files and folders
foreach($files as $file){
//if it is a directory then re-call unlinkr function to delete files inside this directory
if (is_dir($file) and !in_array($file, array('..', '.'))) {
echo "<p>opening directory $file </p>";
unlinkr($file, $pattern);
//remove the directory itself
echo "<p> deleting directory $file </p>";
rmdir($file);
} else if(is_file($file) and ($file != __FILE__)) {
// make sure you don't delete the current script
echo "<p>deleting file $file </p>";
unlink($file);
}
}
}
if you want to delete all files and folders where you place this script then call it as following
//get current working directory
$dir = getcwd();
unlinkr($dir);
if you want to just delete just php files then call it as following
unlinkr($dir, "*.php");
you can use any other path to delete the files as well
unlinkr("/home/user/temp");
This will delete all files in home/user/temp directory.
Another solution:
This Class delete all files, subdirectories and files in the sub directories.
class Your_Class_Name {
/**
* #see http://php.net/manual/de/function.array-map.php
* #see http://www.php.net/manual/en/function.rmdir.php
* #see http://www.php.net/manual/en/function.glob.php
* #see http://php.net/manual/de/function.unlink.php
* #param string $path
*/
public function delete($path) {
if (is_dir($path)) {
array_map(function($value) {
$this->delete($value);
rmdir($value);
},glob($path . '/*', GLOB_ONLYDIR));
array_map('unlink', glob($path."/*"));
}
}
}
Posted a general purpose file and folder handling class for copy, move, delete, calculate size, etc., that can handle a single file or a set of folders.
https://gist.github.com/4689551
To use:
To copy (or move) a single file or a set of folders/files:
$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');
Delete a single file or all files and folders in a path:
$files = new Files();
$results = $files->delete('source/folder/optional-file.name');
Calculate the size of a single file or a set of files in a set of folders:
$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');
<?
//delete all files from folder & sub folders
function listFolderFiles($dir)
{
$ffs = scandir($dir);
echo '<ol>';
foreach ($ffs as $ff) {
if ($ff != '.' && $ff != '..') {
if (file_exists("$dir/$ff")) {
unlink("$dir/$ff");
}
echo '<li>' . $ff;
if (is_dir($dir . '/' . $ff)) {
listFolderFiles($dir . '/' . $ff);
}
echo '</li>';
}
}
echo '</ol>';
}
$arr = array(
"folder1",
"folder2"
);
for ($x = 0; $x < count($arr); $x++) {
$mm = $arr[$x];
listFolderFiles($mm);
}
//end
?>
For me, the solution with readdir was best and worked like a charm. With glob, the function was failing with some scenarios.
// Remove a directory recursively
function removeDirectory($dirPath) {
if (! is_dir($dirPath)) {
return false;
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
if ($handle = opendir($dirPath)) {
while (false !== ($sub = readdir($handle))) {
if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
$file = $dirPath . $sub;
if (is_dir($file)) {
removeDirectory($file);
} else {
unlink($file);
}
}
}
closedir($handle);
}
rmdir($dirPath);
}
public static function recursiveDelete($dir)
{
foreach (new \DirectoryIterator($dir) as $fileInfo) {
if (!$fileInfo->isDot()) {
if ($fileInfo->isDir()) {
recursiveDelete($fileInfo->getPathname());
} else {
unlink($fileInfo->getPathname());
}
}
}
rmdir($dir);
}
I've built a really simple package called "Pusheh". Using it, you can clear a directory or remove a directory completely (Github link). It's available on Packagist, also.
For instance, if you want to clear Temp directory, you can do:
Pusheh::clearDir("Temp");
// Or you can remove the directory completely
Pusheh::removeDirRecursively("Temp");
If you're interested, see the wiki.
I updated the answer of #Stichoza to remove files through subfolders.
function glob_recursive($pattern, $flags = 0) {
$fileList = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$subPattern = $dir.'/'.basename($pattern);
$subFileList = glob_recursive($subPattern, $flags);
$fileList = array_merge($fileList, $subFileList);
}
return $fileList;
}
function glob_recursive_unlink($pattern, $flags = 0) {
array_map('unlink', glob_recursive($pattern, $flags));
}
This is a simple way and good solution. try this code.
array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));

PHP - How to count lines of code in an application [duplicate]

This question already has answers here:
count lines in a PHP project [closed]
(7 answers)
Closed 9 years ago.
I need to count the number of lines of code within my application (in PHP, not command line), and since the snippets on the web didn't help too much, I've decided to ask here.
Thanks for any reply!
EDIT
Actually, I would need the whole snippet for scanning and counting lines within a given folder. I'm using this method in CakePHP, so I'd appreciate seamless integration.
To do it over a directory, I'd use an iterator.
function countLines($path, $extensions = array('php')) {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path)
);
$files = array();
foreach ($it as $file) {
if ($file->isDir() || $file->isDot()) {
continue;
}
$parts = explode('.', $file->getFilename());
$extension = end($parts);
if (in_array($extension, $extensions)) {
$files[$file->getPathname()] = count(file($file->getPathname()));
}
}
return $files;
}
That will return an array with each file as the key and the number of lines as the value. Then, if you want only a total, just do array_sum(countLines($path));...
You can use the file function to read the file and then count:
$c = count(file('filename.php'));
$fp = "file.php";
$lines = file($fp);
echo count($lines);
Using ircmaxell's code, I made a simple class out of it, it works great for me now
<?php
class Line_Counter
{
private $filepath;
private $files = array();
public function __construct($filepath)
{
$this->filepath = $filepath;
}
public function countLines($extensions = array('php'))
{
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->filepath));
foreach ($it as $file)
{
// if ($file->isDir() || $file->isDot())
if ($file->isDir() )
{
continue;
}
$parts = explode('.', $file->getFilename());
$extension = end($parts);
if (in_array($extension, $extensions))
{
$files[$file->getPathname()] = count(file($file->getPathname()));
}
}
return $files;
}
public function showLines()
{
echo '<pre>';
print_r($this->countLines());
echo '</pre>';
}
public function totalLines()
{
return array_sum($this->countLines());
}
}
// Get all files with line count for each into an array
$loc = new Line_Counter('E:\Server\htdocs\myframework');
$loc->showLines();
echo '<br><br> Total Lines of code: ';
echo $loc->totalLines();
?>
PHP Classes has a nice class for counting lines for php files in a directory:
http://www.phpclasses.org/package/1091-PHP-Calculates-the-total-lines-of-code-in-a-directory.html
You can specify the file types you want to check at the top of the class.
https://github.com/sebastianbergmann/phploc
a little dirty, but you can also use system / exec / passthru wc -l *

Categories