I guarante this Different than normally Store to Array.
I dont know how to name it in Tittle about what im asked !!
First : sorry for Bad English.
So just see this below ...
Second :
a. im use build in server : php artisan serve
b. framework is Laravel 5.4
I have url http://127.0.0.1:8000/file/999090/img/img-2as
host : 127.0.0.1:8000 etc
main-folder : {/file} Where i store my image
folder-id : {/990909} This is just id for each folder
sub-folder : {/img} Each id has many sub folder [example]
filde-name : {/img2-as} Just file name [example]
So this is question :
I wanna have array like this in PHP :
$array = [
0 => '/file',
1 => '/file/990909',
2 => '/file/990909/img',
3 => '/file/990909/img/img-2as'
];
try this
$root = '/'; // !!! CHANGE THIS WITH YOUR OWN FOLDER!!!
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
$paths = array($root);
foreach ($iter as $path => $dir) {
if ($dir->isDir()) {
$paths[] = $path;
}
}
print_r($paths);
I already manage just like this :
$parts = "assets/theme/dist/img//img/user2-160x160.jpg";
$path = explode('/', $parts);
for($i=0;$i<count($path);$i++){
for($j=0;$j<$i;$j++){
echo "/".$path[$j];
}
echo "\n";
}
And result is :
/assets
/assets/
/assets/theme/dist
/assets/theme/dist/img
/assets/theme/dist/img/
/assets/theme/dist/img/img
That is what i want have in array and i already try use array_push, but the result is worse.
Im already found it. Just copy in your php file.
$path = "assets/adminlte/dist/img/user2-160x160";
$asd = explode( '/', $path );
$num = count($asd)-1;
$arr = [];
for($i=0;$i<count($asd);$i++) {
for($j=0;$j<=$i;$j++){
#$arr[$i] .= "/".$asd[$j];
}
}
echo "\n";
print_r($arr);
Related
I got this PHP function which returns an array of all files using PHP's ftp_rawlist() and it is working well for me...
However, I currently have no way of knowing the path the returned filename is located in on the FTP server. Does anyone have any ideas on how I can also get the path to the file location on the FTP server along with the name of the file ?
function listDetailed($resource, $directory) {
if (is_array($children = #ftp_rawlist($resource, $directory,true))) {
$items = array();
foreach ($children as $child) {
$chunks = preg_split("/\s+/", $child);
#list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'],$item['month'], $item['day'], $item['time'], $item['filename']) = $chunks;
#$item['type'] = $chunks[0]{0} === 'd' ? 'directory' : 'file';
#array_splice($chunks, 0, 8);
#$items[implode(" ", $chunks)] = $item;
}
return $items;
}
// Throw exception or return false < up to you
}
You just need to add $directory path to start of a filename .
for example :
/*... some codes This exactly */
#list($item['time'], $item['filename'], $directory.'/'.$item['filename']) = $chunks;
The idea is to have an index page with an automatically generated link to each folder in a certain directory.
Each of these folders contains a sort.txt containing just a number, and an name.txt containing the name of the link.
I want to use the content of all the sort.txt files to sort the order of the links, and the content of each name.txt to be displayed as the link name.
So far, I have this:
<?php
$Mydir = './';
$folders = glob($Mydir.'[^EXCLUDE]*', GLOB_ONLYDIR);
$dir = str_replace($Mydir, '', $dir);
sort($dir);
foreach($folders as $key => $dir) {
$taskSort = file_get_contents($dir. "/sort.txt");
$file = ($dir. "/name.txt");
$f = fopen($file, "r");
if ( $line = fgets($f, 1000))
echo '<p>⍆ ' . $line . '' . $taskSort . '
<br />';
}
?>
I manage to use name.txt for the link name, but not to sort them according to sort.txt. how do I achieve that $taskSort is used to sort the links?
Sorry I am not a php professional...
Thanks
When you don't know the architecture (how many folders you can iterate) I like to use the recursive directory iterator class. I give you a fast sample. I don't test it so maybe I forget something. I let you add some extra check (eg: file is writable ?).
However, you don't give enough informations about what are inside sort.txt. By the way I suggest you one possible way. I fill an array with all links and supposed that your $taskSort allow you to sort your array at the end of the iteration.
$oIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(DIRECTORY_PATH));
$aArrayOfLinks = array();
while($oIterator->valid()) {
// For each file found
if( $oIterator->getExtension() == 'txt') {
// Missing additionnal check here
$sHandle = fopen($oIterator->getPathName, "r");
if ( $sLine = fgets($sHandle, 1000)) {
$sDirectory = basename($_oIterator->getPath())
// if sort.txt is in the dir path maybe you should add a particular case
$taskSort = file_get_contents($sDirectory. "/sort.txt");
$aArrayOfLinks[$taskSort] = '<p>⍆ ' . $sLine . '';
}
fclose($sHandle);
}
// Next occurrence
$oIterator->next();
}
// sort your $aArrayOfLinks following the content of $taskSort (which I don't know)
To help you, the class RecursiveDirectoryIterator extends the FilesystemIterator you can get all his methods.
If this sample is to hard/not KISS. You can save all links in an array like the following (update and using your code):
if ( $line = fgets($f, 1000))
$aArrayOfLinks[$taskSort] = '<p>⍆ ' . $line . '' . $taskSort . ';
And then sort the $aArrayOfLinks but one more time I don't know what are inside $taskSort
Edit:
Following your comment with what's inside your sort.txt. I suggest you to use the ksort(). For instance:
$array = array(03 => 'value1', 02 => 'value2', 01 => 'value3');
ksort($array);
echo'<pre>';print_r($array);echo'</pre>';
Output:
Array
(
[1] => value3
[2] => value2
[3] => value1
)
thanks debflav, it took me a while, now it works! this is how it looks now:
<?php
$Mydir = './'; ### OR MAKE IT 'yourdirectory/';
$folders = glob($Mydir.'[^EXCLUDE]*', GLOB_ONLYDIR);
$aArrayOfLinks = array();
foreach($folders as $key => $dir) {
$taskSort = file_get_contents($dir. "/sort.txt");
$file = ($dir. "/name.txt");
$f = fopen($file, "r");
if ( $line = fgets($f, 1000))
$aArrayOfLinks[$taskSort] = '<p>⍆ ' . $line . '<br />';
}
krsort ($aArrayOfLinks);
foreach ($aArrayOfLinks as $value) {
echo $value;
}
?>
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
I'm trying to list directories recrusively in PHP using the RecursiveDirectoryIterator and RecursiveIteratorIterator, but the thing is, i need to ignore some directories and files within..
This is what i have so far..
// Define here the directory you have platform installed.
//
$path = 'testing';
// List of directories / files to be ignored.
//
$ignore_new = array(
# Directories
#
'.git',
'testing/dir1',
'testing/dir2',
'testing/dir3',
'testing/dir8',
'public',
# Files
#
'.gitignore',
'.gitmodules',
'.CHANGELOG.md',
'.README.md',
);
$ite = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($ite) as $filename => $object)
{
echo $filename . '<br />';
}
I've tried different ways to check if the directory/file is in the array, but or it doesn't work, or the directory is not ignored completly...
This an example of the directory structure
testing\
testing\.git
testing\.git\files & directories
testing\testing\dir1
testing\testing\dir2
testing\testing\dir3
testing\testing\dir8
testing\.gitignore
testing\.gitmodules
testing\CHANGELOG.md
testing\README.md
Is this possible, or i need to use the old fashion way to recursive list directories/files in PHP ?
Thanks !
You should always use Full Path since you are combining file and folder
$path = __DIR__;
// List of directories / files to be ignored.
//
$ignoreDir = array('1.MOV.xml','.git','testing/dir1','testing/dir2','testing/dir3','testing/dir8','public');
/**
* Quick patch to add full path to Ignore
*/
$ignoreDir = array_map(function ($var) use($path) {
return $path . DIRECTORY_SEPARATOR . $var;
}, $ignoreDir);
$ite = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
foreach ( new RecursiveIteratorIterator($ite) as $filename => $object ) {
if (in_array($filename, $ignoreDir))
continue;
echo $filename . '<br />';
}
Here is another approach using RecursiveCallbackFilterIterator:
<?php
$f_filter = function ($o_info) {
$s_file = $o_info->getFilename();
if ($s_file == '.git') {
return false;
}
if ($s_file == '.gitignore') {
return false;
}
return true;
};
$o_dir = new RecursiveDirectoryIterator('.');
$o_filter = new RecursiveCallbackFilterIterator($o_dir, $f_filter);
$o_iter = new RecursiveIteratorIterator($o_filter);
foreach ($o_iter as $o_info) {
echo $o_info->getPathname(), "\n";
}
https://php.net/class.recursivecallbackfilteriterator
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;
}