PHP Glob function to find Controller files [duplicate] - php

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;
}

Related

Count array elements returned by scandir(); PHP [duplicate]

This question already has answers here:
Count how many files in directory PHP
(15 answers)
Closed 7 years ago.
I have in folder "files" some folders. I want to return the count of this folders by my php code:
$x = count(scandir('/files'));
echo $x;
But this is not working. What is wrong?
If you have some files in files folder, Here is the solution.
$directory = 'files/';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));//to remove dots
$x = count($scanned_directory);
echo $x;
Try not to use /files. It will look for the file named files
Try this:
$directory = '/your/directory/path/';
$files = glob($directory . '*.*'); // returns an array on success and false on error.
if ( $files !== false )
{
$filecount = count( $files );
echo $filecount;
}
else
{
echo 0;
}
its better to check if directory does even exist first :
$directory = '/your/directory/path/';
if(!is_dir($directory))
die("direction not exists");
ant then count and remove . and .. elements

Get latest 15 files in a directory that are recently added to it php [duplicate]

This question already has answers here:
How to sort files by date in PHP
(6 answers)
Closed 7 years ago.
Suppose there's a directory named "abc"
This directory contains number of files. Out of all these files, I just want latest "X" or latest 15 files in an array(if possible using glob function) in php.
Every help will be greatly appreciable.
// directory for searching files
$dir = "/etc/php5/*";
// getting files with specified four extensions in $files
$files = glob($dir."*.{extension1,extension2,extension3,extension4}", GLOB_BRACE);
// will get filename and filetime in $files
$files = array_combine($files, array_map("filemtime", $files));
// will sort files according to the values, that is "filetime"
arsort($files);
// we don't require time for now, so will get only filenames(which are as keys of array)
$files = array_keys($files);
$starting_index = 0;
$limit = 15;
// will limit the resulted array as per our requirement
$files = array_slice($files, $starting_index,$limit);
// will print the final array
echo "Latest $limit files are as below : ";
print_r($files);
Please improve me, if am wrong
Use the function posted here: http://code.tutsplus.com/tutorials/quick-tip-loop-through-folders-with-phps-glob--net-11274
$dir = "/etc/php5/*";
// Open a known directory, and proceed to read its contents
foreach(glob($dir) as $file)
{
echo "filename: $file : filetype: " . filetype($file) . "<br />";
}
And use filetime() function inside your foreach loop as an IF statement.: http://php.net/manual/en/function.filemtime.php
One way to do this and it's better than glob is to use the RecursiveDirectoryIterator
$dir = new \RecursiveDirectoryIterator('path/to/folder', \FilesystemIterator::SKIP_DOTS);
$it = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST);
$it->setMaxDepth(99); // search for other folders and they child folders
$files = [];
foreach ($it as $file) {
if ($file->isFile()) {
var_dump($file);
}
}
or if you still want to do it with glob
$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
var_dump($file);
}

How do I convert this PHP function to recursively search my directories? [duplicate]

This question already has answers here:
php--glob for searching directories and .jpg only
(2 answers)
Closed 9 years ago.
I have this code right now:
//path to directory to scan
$directory = "./";
//get all image files with a .m4v/.mp4 extension.
$images = glob($directory . "*.{m4v,mp4,mkv}", GLOB_BRACE);
What's the quickest way to convert this to recursively search any subdirectory for the same file types?
You could walk to manual and get from user comments recursive function. glob
You could use RecursiveDirectoryIterator
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
$images = array();
foreach ($objects as $name => $object)
{
/* #var $object SplFileInfo */
if (in_array($object->getExtension(), array('m4v', 'mp4', 'mkv')))
$images[] = $name;
}
function RecursiveGetfiles($dir)
{
$files=array();
foreach(glob('$dir/*') as $d)
{
if(is_dir($d))
{
$files[]=RecursiveGetfiles($d);
}
}
$files=glob($directory . "*.{m4v,mp4,mkv}", GLOB_BRACE);
return $files;
}

Using the RecursiveDirectoryIterator [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Displaying folders and making links of those folders
I'm trying to create a simple file browser using the RecursiveDirectoryIterator but can't seem to figure it out... Any help please?
$cwd = '/path/to/somewhere';
if(isset($_GET['path']) && is_dir($cwd.$_GET['path'])) {
$cwd .= $_GET['path'];
}
$dir = new RecursiveDirectoryIterator($cwd);
$iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
while($iter->valid()) {
// skip unwanted directories
if(!$iter->isDot()) {
if($iter->isDir()) {
// output linked directory along with the number of files contained within
// for example: some_folder (13)
} else {
// output direct link to file
}
}
$iter->next();
}
Not sure if this is the best approach, but I'm under the impression that the RecursiveDirectoryIterator is faster than both the opendir() and glob() methods.
SELF_FIRST and CHILD_FIRST as nothing to do with RecursiveDirectoryIterator but RecursiveIteratorIterator
If you run
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );
foreach ( $iterator as $path ) {
if ($path->isDir()) {
print($path->__toString() . PHP_EOL);
} else {
print($path->__toString() . PHP_EOL);
}
You would get
...\htdocs\lab\stockoverflow\css
...\htdocs\lab\stockoverflow\css\a.css
...\htdocs\lab\stockoverflow\css\b.css
...\htdocs\lab\stockoverflow\css\c.css
...\htdocs\lab\stockoverflow\css\css.php
...\htdocs\lab\stockoverflow\css\css.run.php
If you change it to RecursiveIteratorIterator::CHILD_FIRST
...\htdocs\lab\stockoverflow\css\a.css
...\htdocs\lab\stockoverflow\css\b.css
...\htdocs\lab\stockoverflow\css\c.css
...\htdocs\lab\stockoverflow\css\css.php
...\htdocs\lab\stockoverflow\css\css.run.php
...\htdocs\lab\stockoverflow\css
Can you see the difference is in the position of the current folder

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