I have a folder. I want to put every file in this folder into an array and afterwards I want to echo them all in an foreach loop.
What's the best way to do this?
Thanks!
Scandir is what you're looking for
http://php.net/manual/en/function.scandir.php
<?php
$dir = '/tmp';
$files1 = scandir($dir);
print_r($files1);
?>
Or use combination of opendir and readdir
http://php.net/manual/en/function.readdir.php
Doesn't get much easier than this
http://ca3.php.net/manual/en/function.scandir.php
Don't forget to filter out hidden and parent directories (they start with a dot) on linux.
An Alternative:
define('PATH', 'files/');
$filesArray = array();
$filesArray = glob(PATH . '*', GLOB_ONLYDIR);
This method allow you to specify/filter a by file type. E.G.,
define('PATH', 'files/');
define('FILE_TYPE', '.jpg');
$filesArray = array();
$filesArray = glob(PATH . '*' . FILE_TYPE, GLOB_ONLYDIR);
You can also get the FULL path name to the file by removing the parameter 'GLOB_ONLYDIR'
This works for files and folders in subfolders too. Return list of folders and list of files with their path.
$dir = __DIR__; //work only for this current dir
function listFolderContent($dir,$path=''){
$r = array();
$list = scandir($dir);
foreach ($list as $item) {
if($item!='.' && $item!='..'){
if(is_file($path.$item)){
$r['files'][] = $path.$item;
}elseif(is_dir($path.$item)){
$r['folders'][] = $path.$item;
$sub = listFolderContent($path.$item,$path.$item.'/');
if(isset($sub['files']) && count($sub['files'])>0)
$r['files'] = isset ($r['files'])?array_merge ($r['files'], $sub['files']):$sub['files'];
if(isset($sub['folders']) && count($sub['folders'])>0)
$r['folders'] = array_merge ($r['folders'], $sub['folders']);
}
}
}
return $r;
}
$list = listFolderContent($dir);
var_dump($list['files']);
var_dump($list['folders']);
Edit: dwich answer is better. I will leave this just for information.
readdir.
<?php
if ($handle = opendir('/path/to/dir')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
closedir($handle);
}
?>
Hope this helps.
—Alberto
Related
Let's say I have the following directory tree
tmp
---cat
---dog
---mouse
My index.php is in the same directory as tmp folder. How would I use PHP to save a random folder name as a variable? I've tried the following code but it didn't work.
<?php
function listFolderFiles(){
$dir = './tmp';
$ffs = scandir($dir);
$randomFolder = '';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
$randomFolder = $randomFolder + $ff;
}
}
echo $randomFolder;
echo '</ol>';
}
listFolderFiles();
?>
Another solution can be the built in DirectoryIterator object for iterating through file systems. Just have a look at the following example.
$results = [];
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot() && $fileinfo->isDir()) {
$results[] = $fileinfo->getFilename();
}
}
The given code iterates through a given directory and gives back all directories included in the given directory except the dots.
By create, do you mean return/echo?
I don't think your function will produce a random folder. It will return the last folder.
function listFolderFiles(){
$dir = './tmp';
$Ignore = array('.','..'); // build an ignore array
$Results = array();
$ffs = scandir($dir);
foreach($ffs as $ff){
if(!in_array($ff,$Ignore) && is_dir("./tmp/".$ff)){ // if filename is folder and not in ignore array
$Results[] = $ff; // add filename to results
}
}
shuffle($Results); // shuffle/randomize the results
echo $Results[0];
}
listFolderFiles();
So, I'm familiar with Javascript, HTML, and Python. I have never learned PHP, and at the moment, I'm banging my head against my desk trying to figure out what (to me) seems to be such a simple thing.
I have a folder, with other folders, that contain images.
At the moment, I'm literally just trying to get a list of the folders as links. I get kind of there, but then my output is always reversed! Folder01, Folder02 comes out as Folder02, Folder01. I can't fricken' sort my output. I've been searching constantly trying to figure this out but nothing is working for me.
<?php
function listAlbums(){
if ($handle = opendir('./photos/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo $entry . "<br/>";
}
}
closedir($handle);
}
}
?>
This outputs: Folder02, Folder01. I need it the other way around. I've tried asort, array_reverse, etc. but I must not be using them properly. This is killing me. I never had to even thin about this in Python, or Javascript, unless I actually wanted to have an ascending list...
Try one of these, one is recursive, one is not:
// Recursive
function listAlbums($path = './photos/')
{
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($objects as $name => $object) {
ob_start();
echo rtrim($object,".");
$data = ob_get_contents();
ob_end_clean();
$arr[] = $data;
}
return array_unique($arr);
}
// Non-recursive
function getAlbums($path = './photos/')
{
$objects = dir($path);
while (false !== ($entry = $objects->read())) {
if($entry !== '.' && $entry !== '..')
$arr[] = $path.$entry;
}
$objects->close();
return $arr;
}
// I would use __DIR__, but not necessary
$arr = listAlbums();
$arr2 = getAlbums();
// Reverse arrays by key
krsort($arr);
krsort($arr2);
// Show arrays
print_r($arr);
print_r($arr2);
I try your code and make simple changes and I am able to do what you want to get.
Here is my code ( copy of your code + Modify ) :
function listAlbums() {
$files = array();
if ($handle = opendir('./photos/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
//echo $entry . "<br/>";
$files[] = $entry;
}
}
closedir($handle);
}
// Sort your folder in ascending order
sort($files);
// Sort your folder in descending order [ code commented ]
//rsort($files);
// Check your photos folder has folder or not
if( !empty( $files ) ) {
// Show Your Folders
foreach ($files as $key => $folderName ) {
echo $folderName . "<br/>";
}
} else {
echo 'You have no folder yet in photos directory';
}
}
My Changes:
First store your all folders in the photos directory in an array variable
Secondly sort this array whatever order you want.
Finally show your folders (And your work will be solved)
You can know more about this from sort-and-display-directory-list-alphabetically-using-opendir-in-php
Thanks
Ok, this is the best result i've gotten all night. This does 99% of what I need. But I still can't figure out this damn sort issue. This code will go through a list of directories, and create lightbox galleries out of the images in each folder. However, the first image is always the last one in the array, and I can't figure out how the heck to get it to sort normally! Check line 16 to see where I talking about.
<?php
function listAlbums(){
$directory = "./photos/";
//get all folders in specified directory
$folders = glob($directory . "*");
//get each folder item name
foreach($folders as $folderItem){
//check to see if the folderItem is a folder/directory
if(is_dir($folderItem)){
$count = 0;
foreach (new DirectoryIterator($folderItem) as $fileInfo) {
if($fileInfo->isDot()) continue;
$files = $folderItem."/".$fileInfo->getFilename();
if ($count == 0){ //This is where my issues start. This file ends up being the last one in the list. I need it to be the first.
echo ''.basename($folderItem).'' . "<br/>";
echo "<div style='display: none'>" . "<br/>";
$count++;
}else{
echo ''.basename($folderItem).'' . "<br/>";
}
}echo "</div>";
}
}
}
?>
Whew! Ok, I got everything working. DirectoryIterator was pissing me off with its random print order. So I fell back to just glob and scandir. Those seem to print out a list "logically". To summarize, this bit of php will grab folders of images and turn each folder into its own lightbox gallery. Each gallery shows up as a hyperlink that triggers the lightbox gallery. I'm pretty happy with it!
So here's my final code:
<?php
function listAlbums(){
$directory = "./photos/";
//get all folders in specified directory
$folders = glob($directory . "*");
//get each folder item name
foreach($folders as $folderItem){
//check to see if the folderItem is a folder/directory
if(is_dir($folderItem)){
$count = 0;
$scanDir = scandir($folderItem);
foreach($scanDir as $file){
if ($file === '.' || $file === '..') continue;
$filePath = $folderItem."/".$file;
if ($count == 0){
echo ''.basename($folderItem).'' . "<br/>";
echo "<div style='display: none'>" . "<br/>";
$count++;
}else{
echo ''.basename($folderItem).'' . "<br/>";
}
}echo "</div>";
}
}
}
Special thanks to Rasclatt for bearing with me through all of this and offering up a lot of hand-holding and help. I really appreciate it!
Can any one please let me know how to read the directory and find what are the files and directories inside that directory.
I've tried with checking the directories by using the is_dir() function as follows
$main = "path to the directory";//Directory which is having some files and one directory
readDir($main);
function readDir($main) {
$dirHandle = opendir($main);
while ($file = readdir($dirHandle)) {
if ($file != "." && $file != "..") {
if (is_dir($file)) {
//nothing is coming here
}
}
}
}
But it is not checking the directories.
Thanks
The most easy way in PHP 5 is with RecursiveDirectoryIterator and RecursiveIteratorIterator:
$dir = '/path/to/dir';
$directoryIterator = new RecursiveDirectoryIterator($dir);
$iterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $path) {
if ($path->isDir()) {
// ...
}
}
You don't need to recurse by yourself as these fine iterators handle it by themselves.
For more information about these powerful iterators see the linked documentation articles.
You have to use full path to subdirectory:
if(is_dir($main.'/'.$file)) { ... }
Use scandir
Then parse the result and eliminate '.' and '..' and is_file()
$le_map_to_search = $main;
$data_to_use_maps[] = array();
$data_to_use_maps = read_dir($le_map_to_search, 'dir');
$aantal_mappen = count($data_to_use_maps);
$counter_mappen = 1;
while($counter_mappen < $aantal_mappen){
echo $data_to_use_maps[$counter_mappen];
$counter_mappen++;
}
$data_to_use_files[] = array();
$data_to_use_files = read_dir($le_map_to_search, 'files');
$aantal_bestanden = count($data_to_use_files);
$counter_files = 1;
while($counter_files < $aantal_files){
echo $data_to_use_files [$counter_files ];
$counter_files ++;
}
Look at the reference here:
http://php.net/manual/en/function.scandir.php
Try this
$handle = opendir($directory); //Open the directory
while (false !== ($file = readdir($handle))) {
$filepath = $directory.DS.$file; //Get all files/directories in the directory
}
I have this working function that finds folders and creates an array.
function dua_get_files($path)
{
foreach (glob($path . "/*", GLOB_ONLYDIR) as $filename)
{
$dir_paths[] = $filename;
}
return $dir_paths;
}
This function can only find the directories on the current location. I want to find the directory paths in the child folders and their children and so on.
The array should still be a flat list of directory paths.
An example of how the output array should look like
$dir_path[0] = 'path/folder1';
$dir_path[1] = 'path/folder1/child_folder1';
$dir_path[2] = 'path/folder1/child_folder2';
$dir_path[3] = 'path/folder2';
$dir_path[4] = 'path/folder2/child_folder1';
$dir_path[5] = 'path/folder2/child_folder2';
$dir_path[6] = 'path/folder2/child_folder3';
If you want to recursively work on directories, you should take a look at the RecursiveDirectoryIterator.
$path = realpath('/etc');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}
Very strange - everybody advice recursion, but better just cycle:
$dir ='/dir';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
$dir .= '/*';
if(!$result) {
$result = $dirs;
} else {
$result = array_merge($result, $dirs);
}
}
Try this instead:
function dua_get_files($path)
{
$data = array();
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
if (is_dir($file) === true)
{
$data[] = strval($file);
}
}
return $data;
}
Use this function :
function dua_get_files($path)
{
$dir_paths = array();
foreach (glob($path . "/*", GLOB_ONLYDIR) as $filename)
{
$dir_paths[] = $filename;
$a = glob("$filename/*", GLOB_ONLYDIR);
if( is_array( $a ) )
{
$b = dua_get_files( "$filename/*" );
foreach( $b as $c )
{
$dir_paths[] = $c;
}
}
}
return $dir_paths;
}
You can use php GLOB function, but you must create a recursive function to scan directories at infinite level depth. Then store results in a global variable.
function dua_get_files($path) {
global $dir_paths; //global variable where to store the result
foreach ($path as $dir) { //loop the input
$dir_paths[] = $dir; //can use also "basename($dir)" or "realpath($dir)"
$subdir = glob($dir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR); //use DIRECTORY_SEPARATOR to be OS independent
if (!empty($subdir)) { //if subdir is not empty make function recursive
dua_get_files($subdir); //execute the function again with current subdir
}
}
}
//usage:
$path = array('galleries'); //suport absolute or relative path. support one or multiple path
dua_get_files($path);
print('<pre>'.print_r($dir_paths,true).'</pre>'); //debug
For PHP, if you are on a linux/unix, you can also use backticks (shell execution) with the unix find command. Directory searching on the filesystem can take a long time and hit a loop -- the system find command is already built for speed and to handle filesystem loops. In other words, the system exec call is likely to cost far less cpu-time than using PHP itself to search the filesystem tree.
$dirs = `find $path -type d`;
Remember to sanitize the $path input, so other users don't pass in security compromising path names (like from the url or something).
To put it into an array
$dirs = preg_split("/\s*\n+\s*/",`find $path -type d`,-1,PREG_SPLIT_NO_EMPTY);
PHP manual for scandir: By default, the sorted order is alphabetical in ascending order.
I'm building a file browser (in Windows), so I want the addresses to be returned sorted by folder/file, then alphabetically in those subsets.
Example: Right now, I scan and output
Aardvark.txt
BarDir
BazDir
Dante.pdf
FooDir
and I want
BarDir
BazDir
FooDir
Aardvark.txt
Dante.pdf
Other than a usort and is_dir() solution (which I can figure out myself), is there a quick and efficient way to do this?
The ninja who wrote this comment is on the right track - is that the best way?
Does this give you what you want?
function readDir($path) {
// Make sure we have a trailing slash and asterix
$path = rtrim($path, '/') . '/*';
$dirs = glob($path, GLOB_ONLYDIR);
$files = glob($path);
return array_unique(array_merge($dirs, $files));
}
$path = '/path/to/dir/';
readDir($path);
Note that you can't glob('*.*') for files because it picks up folders named like.this.
Please try this. A simple function to sort the PHP scandir results by files and folders (directories):
function sort_dir_files($dir)
{
$sortedData = array();
foreach(scandir($dir) as $file)
{
if(is_file($dir.'/'.$file))
array_push($sortedData, $file);
else
array_unshift($sortedData, $file);
}
return $sortedData;
}
I'm late to the party but I like to offer my solution with readdir() rather than with glob(). What I was missing from the solution is a recursive version of your solution. But with readdir it's faster than with glob.
So with glob it would look like this:
function myglobdir($path, $level = 0) {
$dirs = glob($path.'/*', GLOB_ONLYDIR);
$files = glob($path.'/*');
$all2 = array_unique(array_merge($dirs, $files));
$filter = array($path.'/Thumbs.db');
$all = array_diff($all2,$filter);
foreach ($all as $target){
echo "$target<br />";
if(is_dir("$target")){
myglobdir($target, ($level+1));
}
}
}
And this one is with readdir but has basically the same output:
function myreaddir($target, $level = 0){
$ignore = array("cgi-bin", ".", "..", "Thumbs.db");
$dirs = array();
$files = array();
if(is_dir($target)){
if($dir = opendir($target)){
while (($file = readdir($dir)) !== false){
if(!in_array($file, $ignore)){
if(is_dir("$target/$file")){
array_push($dirs, "$target/$file");
}
else{
array_push($files, "$target/$file");
}
}
}
//Sort
sort($dirs);
sort($files);
$all = array_unique(array_merge($dirs, $files));
foreach ($all as $value){
echo "$value<br />";
if(is_dir($value)){
myreaddir($value, ($level+1));
}
}
}
closedir($dir);
}
}
I hope someone might find this useful.