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 *
Related
This question already has answers here:
php glob - scan in subfolders for a file
(4 answers)
Closed 4 years ago.
I try to find all the controller files of a java code repository in php script.(Lets say CustomerController.java for example)
Here is the solution i have tried to achieve this goal:
$fileScan = glob($currentDirectory . "**/*Controller.java");
But it returns nothing. I have also tried different combinations like:
"**Controller*.java", "*/*Controller*.java" etc.
But not luck.
Am i missing something here about glob function?
Use RecursiveDirectoryIterator
<?php
function rsearch($folder, $pattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
$fileList = array();
foreach($files as $file) {
$fileList = array_merge($fileList, $file);
}
return $fileList;
}
?>
Try following code. It will find the files with "Controller.java"
foreach (glob("*Controller.java") as $filename)
{
echo $filename;
}
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does glob() have negation?
I want to delete all files from a directory (could be any number of file extentions) apart from the single index.html in there.
I'm using:
$path = "/assets/cache/";
foreach(glob($path ."*.*") as $file) {
unlink($file);
}
But can't for the life of me how to say unlink, if not .html!
Thanks!
Try this here...
$path = "/assets/cache/";
foreach(glob($path ."*.*") as $file) {
$pathPart = explode(".",$file);
$fileEx = $pathPart[count($pathPart)-1];
if($fileEx != "html" && $fileEx != "htm"){
unlink($file);
}
}
try
$path = "/assets/cache/";
foreach(glob($path ."*.*") as $file) {
if(pathinfo($file, PATHINFO_EXTENSION) != 'html') {
unlink($file);
}
}
if you want to delete other html files also (apart from "index.html"):
$path = "/assets/cache/";
foreach(glob($path ."*.*") as $file) {
if(pathinfo($file, PATHINFO_BASENAME) != 'index.html') {
unlink($file);
}
}
The php function glob has no negation, however PHP can give you the difference between two globs via array_diff:
$all = glob("*.*");
$not = glob("php_errors.log");
var_dump(
$all,
$not,
array_diff($all, $not)
);
See the demo: http://codepad.org/RBFwPUWm
If you do not want to use arrays, I highly suggest to take a look into PHPs directory iterators.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Finding a file with a specific name with any extension
i've this code for put into an array all the files contained into a directory
$directory = "./";
$ourDirList = scandir($directory);
$arraylistafiles=array();
foreach($ourDirList as $ourItem)
{
if (is_file($ourDir . $ourItem))
{$arraylistafiles[]=$ourItem;}
}
but if i want to put only the file that have ".jpg" extension, what i can do?
Using PHP's glob() you can avoid the is_file() call because glob will only return files that actually exist in the directory. There is no need to create a UDF (user defined function) in your case.
$dir = './';
foreach(glob($dir.'*.jpg') as $file) {
print $file . "\n";
}
UPDATE
From your comment it's clear that you don't understand how glob() works. You can achieve what you're trying to do like this:
$arraylistafiles = glob($dir.'*.jpg');
if(is_file($ourDir.$ourItem) && substr($ourItem,-4) == '.jpg') {
//
}
You can use bellow function.
public function getFileList($dirpath,$list_ignore,$list_allowed_ext)
{
$filelist = array();
if ($handle = opendir(dirname ($dirpath)))
{
while (false !== ($file = readdir($handle)))
{
if (!is_dir($file) && !in_array($file,$list_ignore) && in_array(strtolower(end(explode('.',$file))),$list_allowed_ext))
{
$filelist[] = $file;
}
}
closedir($handle);
}
return $filelist;
}
Implementation will be looks like..
$fileTypes = array ("jpg");
$list_ignore = array ('.','..');
$fileList = getFileList("./",$list_ignore,$fileTypes);
Cheers!
First you have to check for the file extension for the file in foreach array. . If the extension is jpg then add that item into the new array. . . Hope you understand. .
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/