I have searched SO and went through all of them. Many don't seem to apply to my problem but supplied information that I tried to apply. Result was many parse errors. I can't seem to apply them correctly. This is my first use of iterators. So, after a few days trying I need help.
The original code was taken form the PHP manual. I turned it into a function and added the code to remove dot and dot dot entries (. and ..). I then added code to return an array of files so I can use it in a foreach statement. Problem is that I don't have access to the properties.
<?php
function getDirectoryListing($path)
{
$dir_iterator = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
$files = array();
foreach($iterator as $file)
{
if(strpos($file, ".", -1) !== false)
{
continue;
} // Closing brace for if(strpos($file, ".", -1) !== false)
$files[] = $file;
} // Closing brace for foreach($iterator as $file)
return $files;
}
$files = getDirectoryListing("I:\cef-inc.net/images/database/");
print_r($files);
?>
When I print_r $files I get:
Array
(
[0] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => I:\cef-inc.net/images/database\calendar.ico
[fileName:SplFileInfo:private] => calendar.ico
)
)
When I echo $file in the foreach I get the pathName but not the fileName.
What do I need to do in the function to put everything in an array?
Thank you for looking,
Charles
You get an array of SplFileInfo objects. You should use their getFilename() method to access their filename without the path.
When you echo the object, you’re calling __tostring() method.
Related
I have this simple below code to help me get the contents of all files and sub folder. I took this code from the PHP cook book. it says that I can use the isDot() but it doesn't explain how to ..
I tried to put a if just before array but it doesn't work...
if (! $file->isDot())
I don't know how to put both getPathname and isDot when adding to the array.
I've read the PHP net website but don't understand how to fit in.
code:
$dir = new RecursiveDirectoryIterator('/usr/local');
$dircontent = array();
foreach (new RecursiveIteratorIterator($dir) as $file) {
$dircontent [] = $file -> getPathname();
}
print_r($dircontent);
Use the FilesystemIterator::SKIP_DOTS flag in your RecursiveDirectoryIterator to get rid of dot files:
$dir = '/usr/local';
$result = array();
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$dir,
FilesystemIterator::SKIP_DOTS
)
);
foreach ($files as $file) {
$result[] = $file->getPathname();
}
print_r($result);
The reason isDot() is failing is that your $file variable holds a SplFileInfo object, not a DirectoryIterator.
I want to use array_slice with scandir in my PHP script.
Normal usage:
<?php
$files = scandir('/path/to/files');
foreach($files as $file) {
if($file != '.' && $file != '..') {
// Do something here...
}
}
My example:
<?php
$files = array_slice(scandir('/path/to/files'), 2);
foreach($files as $file) {
// Do something here...
}
My doubt is, is it safe or not to use this type of logic ?
It is definitely not safe. The following example creates a directory with a file called !. When scandir sorts the results, ! appears before . and ..:
mkdir('test');
touch('test/!');
print_r(scandir('test'));
unlink('test/!');
rmdir('test');
Output:
Array
(
[0] => !
[1] => .
[2] => ..
)
In general, this will be an issue for all filenames starting with a character which sorts before .. That includes some unprintable characters which probably won't exist in real world data, but it also applies to common punctuation including ! # $ % & ( ) + -.
Even if it worked, I wouldn't recommend it, as using array_slice there makes the intent of the code less clear.
Instead of trying to scan directory by old-school ways, i strongly recommend using of SPL Directory Iterator for such requirement.
Try this:
$iterator = new \DirectoryIterator('/path/to/files');
foreach ($iterator as $file) {
if($file->isDot()) {
continue;
}
/** Now here you can use lot of SplFileInfo interface methods here */
// $file->getFilename();
// $file->isFile();
// $file->isDir();
// $file->getSize();
}
I am trying to get a matched array of files using scandir() and foreach().
when I run scandir() then it returns all file list. Its okey here.
now in second step when I do foreach scandir()s array then I get only one matched file. but there are two files called (please note before doing foreach my scandir() returns all files including this two files);
widget_lc_todo.php
widget_lc_notes.php
something is missing in my code, I dont know what :-(
here is my code:
$path = get_template_directory().'/templates';
$files = scandir($path);
print_r($files);
$template = array();
foreach ($files as $file){
if(preg_match('/widget_lc?/', $file)):
$template[] = $file;
return $template;
endif;
}
print_r($template);
Your code above is calling return as soon as it finds the first matching file, which means that the foreach loop exits as soon as preg_match returns true. You should not return until after the foreach loop exits:
// ...
foreach ($files as $file){
if(preg_match('/widget_lc?/', $file)) {
$template[] = $file;
}
}
return $template;
// ...
I want to get a list of all the subdirectories and my below code works except when I have readonly permissions on certain folders.
In the below question it shows how to skip a directory with RecursiveDirectoryIterator
Can I make RecursiveDirectoryIterator skip unreadable directories? however my code is slightly different here and I am not able to get around the problem.
$path = 'www/';
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::KEY_AS_PATHNAME),
RecursiveIteratorIterator::CHILD_FIRST) as $file => $info)
{
if ($info->isDir())
{
echo $file . '<br>';
}
}
I get the error
Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(../../www/special): failed to open dir: Permission denied'
I have tried replacing it with the accepted answer in the other question.
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("."),
RecursiveIteratorIterator::LEAVES_ONLY,
RecursiveIteratorIterator::CATCH_GET_CHILD);
However this code will not give me a list of all the directories inside of www like I want, where am I going wrong here?
Introduction
The main issue with your code is using CHILD_FIRST
FROM PHP DOC
Optional mode. Possible values are
RecursiveIteratorIterator::LEAVES_ONLY - The default. Lists only leaves in iteration.
RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.
RecursiveIteratorIterator::CHILD_FIRST - Lists leaves and parents in iteration with leaves coming first.
What you should use is SELF_FIRST so that the current directory is included. You also forgot to add optional parameters RecursiveIteratorIterator::CATCH_GET_CHILD
FROM PHP DOC
Optional flag. Possible values are RecursiveIteratorIterator::CATCH_GET_CHILD which will then ignore exceptions thrown in calls to RecursiveIteratorIterator::getChildren().
Your CODE Revisited
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::KEY_AS_PATHNAME),
RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD) as $file => $info)
{
if ($info->isDir())
{
echo $file . '<br>';
}
}
You really want CHILD_FIRST
If you really want to maintain the CHILD_FIRST structure then i suggest you use ReadableDirectoryIterator
Example
foreach ( new RecursiveIteratorIterator(
new ReadableDirectoryIterator($path),RecursiveIteratorIterator::CHILD_FIRST) as $file ) {
echo $file . '<br>';
}
Class Used
class ReadableDirectoryIterator extends RecursiveFilterIterator {
function __construct($path) {
if (!$path instanceof RecursiveDirectoryIterator) {
if (! is_readable($path) || ! is_dir($path))
throw new InvalidArgumentException("$path is not a valid directory or not readable");
$path = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
}
parent::__construct($path);
}
public function accept() {
return $this->current()->isReadable() && $this->current()->isDir();
}
}
function dirScan($dir, $fullpath = false){
$ignore = array(".","..");
if (isset($dir) && is_readable($dir)){
$dlist = array();
$dir = realpath($dir);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir,RecursiveDirectoryIterator::KEY_AS_PATHNAME),RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach($objects as $entry){
if(!in_array(basename($entry), $ignore)){
if (!$fullpath){
$entry = str_replace($dir, '', $entry);
}
$dlist[] = $entry;
}
}
return $dlist;
}
}
This code works 100%...
You can simply use this function in order to scan for files and folders in your desired directory or drive. You just need to pass the path of the desired directory into the function. The second parameter of the function is to show full-path of the scanned files and folder. False value of the second parameter means not to show full-path.
The array $ignore is used to exclude any desired filename or foldername from the listing.
The function returns the array containing list of files and folders.
This function skips the files and folders that are unreadable while recursion.
I've set up the following directory structure:
/
test.php <-- the test script
www/
test1/ <-- permissions = 000
file1
test2/
file2
file3
I ran the following code (I've added the SKIP_DOTS flag to skip . and .. btw):
$i = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("www", FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY,
RecursiveIteratorIterator::CATCH_GET_CHILD
);
print_r(iterator_to_array($i));
It outputs the following:
Array
(
[www/test2/file2] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => www/test2/file2
[fileName:SplFileInfo:private] => file2
)
[www/file3] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => www/file3
[fileName:SplFileInfo:private] => file3
)
)
This works as expected.
Update
Added the flags you've had in your original example (although I believe those are default anyway):
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("www", FilesystemIterator::SKIP_DOTS | FilesystemIterator::KEY_AS_PATHNAME),
RecursiveIteratorIterator::LEAVES_ONLY,
RecursiveIteratorIterator::CATCH_GET_CHILD | RecursiveIteratorIterator::CHILD_FIRST
) as $file => $info) {
echo $file, "\n";
print_r($info);
if ($info->isDir()) {
echo $file . '<br>';
}
}
Output:
www/test2/file2
SplFileInfo Object
(
[pathName:SplFileInfo:private] => www/test2/file2
[fileName:SplFileInfo:private] => file2
)
www/file3
SplFileInfo Object
(
[pathName:SplFileInfo:private] => www/file3
[fileName:SplFileInfo:private] => file3
)
<?php
$path = "D:/Movies";
$directory_iterator = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
$files = new RecursiveIteratorIterator($directory_iterator,
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD);
try {
foreach( $files as $fullFileName => $file) {
$path_parts = pathinfo($fullFileName);
if(is_file($fullFileName)){
$path_parts = pathinfo($fullFileName);
$fileName[] = $path_parts['filename'];
$extensionName[] = $path_parts['extension'];
$dirName[] = $path_parts['dirname'];
$baseName[] = $path_parts['basename'];
$fullpath[] = $fullFileName;
}
}
foreach ($fullpath as $filles){
echo $filles;
echo "</br>";
}
}
catch (UnexpectedValueException $e) {
printf("Directory [%s] contained a directory we can not recurse into", $directory);
}
?>
The glob function skips read errors automatically and should simplify your code a bit as well.
If you are getting unhandled exceptions, why don't you put that code in a try block, with an exception catch block to catch errors when it can't read directories? Just a simple suggestion by looking at your code and your problem. There is probably a neater way to do it in PHP.
You need to use SELF_FIRST constant if you want to return the unreadable directory name.
When you're doing CHILD_FIRST, it attempt to get into the directory, fails, and the current directory name is not included.
$path = 'testing';
$directory_iterator = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
$iterator = new RecursiveIteratorIterator($directory_iterator,
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach ($iterator as $file => $info) {
if ($info->isDir()) {
echo $file . "\n";
}
}
What about try catch the UnexpectedValueException. Maybe there is even an unique exception code for that error you can check. Otherwise you can evil parse exception message for "permission denied".
I would suggest to examine the http://php.net/manual/de/class.unexpectedvalueexception.php
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;
}