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
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;
}
Using the unlink function in php is it possible to search a directory with multiple folders for txt files with a certain name. In my case Newsfeed.txt
Where should I start with this ?
Great answer maxhb. Here's something a little more manual.
<?php
function unlink_newsfeed($checkThisPath) {
$undesiredFileName = 'Newsfeed.txt';
foreach(scandir($checkThisPath) as $path) {
if (preg_match('/^(\.|\.\.)$/', $path)) {
continue;
}
if (is_dir("$checkThisPath/$path")) {
unlink_newsfeed("$checkThisPath/$path");
} else if (preg_match( "/$undesiredFileName$/", $path)) {
unlink("$checkThisPath/$path");
}
}
}
unlink_newsfeed(__DIR__);
You could use the recursive directory iterators of the php standard library (SPL).
function deleteFileRecursive($path, $filename) {
$dirIterator = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator(
$dirIterator,
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if(basename($file) == $filename) unlink($file);
}
}
deleteFileRecursive('/path/to/delete/from/', 'Newsfeed.txt');
This will allow you to delete all files with name Newsfeed.txt from the given folder and all subfolders.
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);
}
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
This question already has answers here:
How to read a list of files from a folder using PHP? [closed]
(9 answers)
Closed 7 years ago.
I have been trying to figure out a way to list all files contained within a directory. I'm not quite good enough with php to solve it on my own so hopefully someone here can help me out.
I need a simple php script that will load all filenames contained within my images directory into an array. Any help would be greatly appreciated, thanks!
Try glob
Something like:
foreach(glob('./images/*.*') as $filename){
echo $filename;
}
scandir() - List files and directories inside the specified path
$images = scandir("images", 1);
print_r($images);
Produces:
Array
(
[0] => apples.jpg
[1] => oranges.png
[2] => grapes.gif
[3] => ..
[4] => .
)
Either scandir() as suggested elsewhere or
glob() — Find pathnames matching a pattern
Example
$images = glob("./images/*.gif");
print_r($images);
/* outputs
Array (
[0] => 'an-image.gif'
[1] => 'another-image.gif'
)
*/
Or, to walk over the files in directory directly instead of getting an array, use
DirectoryIterator — provides a simple interface for viewing the contents of filesystem directories
Example
foreach (new DirectoryIterator('.') as $item) {
echo $item, PHP_EOL;
}
To go into subdirectories as well, use RecursiveDirectoryIterator:
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('.'),
RecursiveIteratorIterator::SELF_FIRST
);
foreach($items as $item) {
echo $item, PHP_EOL;
}
To list just the filenames (w\out directories), remove RecursiveIteratorIterator::SELF_FIRST
You can also use the Standard PHP Library's DirectoryIterator class, specifically the getFilename method:
$dir = new DirectoryIterator("/path/to/images");
foreach ($dir as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
This will gives you all the files in links.
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/your_folder/";
$files = scandir($path);
$count=1;
foreach ($files as $filename)
{
if($filename=="." || $filename==".." || $filename=="download.php" || $filename=="index.php")
{
//this will not display specified files
}
else
{
echo "<label >".$count.". </label>";
echo "".$filename."
";
$count++;
}
}
?>
Maybe this function can be useful in the future. You can manipulate the function if you need to echo things or want to do other stuff.
$wavs = array();
$wavs = getAllFiles('folder_name',$wavs,'wav');
$allTypesOfFiles = array();
$wavs = getAllFiles('folder_name',$allTypesOfFiles);
//explanation of arguments from the getAllFiles() function
//$dir -> folder/directory you want to get all the files from.
//$allFiles -> to store all the files in and return in the and.
//$extension -> use this argument if you want to find specific files only, else keept empty to find all type of files.
function getAllFiles($dir,$allFiles,$extension = null){
$files = scandir($dir);
foreach($files as $file){
if(is_dir($dir.'/'.$file)) {
$allFiles = getAllFiles($dir.'/'.$file,$allFiles,$extension);
}else{
if(empty($extension) || $extension == pathinfo($dir.'/'.$file)['extension']){
array_push($allFiles,$dir.'/'.$file);
}
}
}
return $allFiles;
}