ls() - Return Folder Contents

The ls() function will take a pattern and a folder as the argument and go through it(recursively if needed)and return the list of all files in that folder.

Arguments

$pattern
The first argument is the pattern(or the file mask) to look out for. Example: ls("*.html"). This supports any pattern supported by the glob function. This is an optional argument - if nothing is given, it defaults to "*". Some possible values...
*Matches everything.
*.phpAll files with the extension php
*.{php,html}Files with extension 'php' or 'html'
file[1-3].phpIt could match file1.php, file2.php and file3.php
$folder
The path of the directory of which directory list you want. This is an optional argument. If empty, the function will assume the value to be the current folder.
$recursively
The function will traverse the folder tree recursively if this is true. Defaults to false.
$options
An array of values 'return_files' or 'return_folders' or both. This decides what must be returned.

Returned Value

A flat array with the path of all the files(no folders) that matches the condition given. An example is...


Array
(
    [0] => 1.php
    [1] => 2.php
    [2] => 3.txt
    [3] => 4.txt
    [4] => 5 5.txt
    [5] => 6/
    [6] => 6/8.css
    [7] => 6/9.html
    [8] => 7/
    [9] => 7/10.net.txt
    [10] => 7/11.php
)

Code


<?php
/**
 * This funtion will take a pattern and a folder as the argument and go thru it(recursivly if needed)and return the list of 
 *               all files in that folder.
 * Link             : http://www.bin-co.com/php/scripts/filesystem/ls/
 * Arguments     :  $pattern - The pattern to look out for [OPTIONAL]
 *                    $folder - The path of the directory of which's directory list you want [OPTIONAL]
 *                    $recursivly - The funtion will traverse the folder tree recursivly if this is true. Defaults to false. [OPTIONAL]
 *                    $options - An array of values 'return_files' or 'return_folders' or both
 * Returns       : A flat list with the path of all the files(no folders) that matches the condition given.
 */
function ls($pattern="*"$folder=""$recursivly=false$options=array('return_files','return_folders')) {
    if(
$folder) {
        
$current_folder realpath('.');
        if(
in_array('quiet'$options)) { // If quiet is on, we will suppress the 'no such folder' error
            
if(!file_exists($folder)) return array();
        }
        
        if(!
chdir($folder)) return array();
    }
    
    
    
$get_files    in_array('return_files'$options);
    
$get_foldersin_array('return_folders'$options);
    
$both = array();
    
$folders = array();
    
    
// Get the all files and folders in the given directory.
    
if($get_files$both glob($patternGLOB_BRACE GLOB_MARK);
    if(
$recursivly or $get_folders$folders glob("*"GLOB_ONLYDIR GLOB_MARK);
    
    
//If a pattern is specified, make sure even the folders match that pattern.
    
$matching_folders = array();
    if(
$pattern !== '*'$matching_folders glob($patternGLOB_ONLYDIR GLOB_MARK);
    
    
//Get just the files by removing the folders from the list of all files.
    
$all array_values(array_diff($both,$folders));
        
    if(
$recursivly or $get_folders) {
        foreach (
$folders as $this_folder) {
            if(
$get_folders) {
                
//If a pattern is specified, make sure even the folders match that pattern.
                
if($pattern !== '*') {
                    if(
in_array($this_folder$matching_folders)) array_push($all$this_folder);
                }
                else 
array_push($all$this_folder);
            }
            
            if(
$recursivly) {
                
// Continue calling this function for all the folders
                
$deep_items ls($pattern$this_folder$recursivly$options); # :RECURSION:
                
foreach ($deep_items as $item) {
                    
array_push($all$this_folder $item);
                }
            }
        }
    }
    
    if(
$folderchdir($current_folder);
    return 
$all;
}

Comments

Patrik at 13 Mar, 2008 10:18
Thanks for that!

To call the function I use this code (used to list music files):

$opt[0]="return_files";
$tracks=ls ("*.{mp3,ogg}","/mnt/mp3",true,$opt);
print_r($tracks);

Reply to this.
Brad at 15 Mar, 2008 02:32
Ha are you reading my mind? The more I look at what you have the more I find things that are really useful for projects that I'm currently working on. So a big thanks!
Reply to this.
mihai at 27 Mar, 2008 02:41
Thank you for your code. I had something similar but yours fits better my needs.
Reply to this.
Abhijit at 05 May, 2008 11:34
Many thanks for this very useful function. YOU ROCK !!!
Reply to this.
Jonny at 17 Jul, 2008 02:19
Hi
Great code, I'am using the code in CLI winXP.
Funny thing it'll only show 290 files in any given folder,
though there's a lot more.
I'am I missing something.

function hav'nt touched it, the function call

$opt[0]="return_files";
$filer=ls ("*","C:/Documents and Settings/Jon/Mina dokument/Visual Studio 2008",true,$opt);
print_r($filer);

Regards Jon
Reply to this.
anarc at 03 Nov, 2008 01:08
I hope it's not just because I'm a complete noob, but every time I've tried using this function it gives me a: "Parse error: syntax error, unexpected T_VARIABLE in ls.php on line 12"

I just copied and pasted to a new php file, I'm guessing that's exactly my problem?!? What did I miss?

Thanks in advance and please forgive me for my surely unworthy query.

anarc
Reply to this.
Binny V A at 04 Nov, 2008 12:09
Is there any other code in the file? The code is working correctly in my system.
Reply to this.
anarc at 04 Nov, 2008 12:42
Thanks for your respose! I have no idea what I was doing wrong but I'm not doing it anymore because now it's working perfectly, I'll have to go with the total noob excuse. I'm very happy it works, but not knowing the reason why it didn't work yesterday will eat at my soul for months to come.

Sorry about that!

And Thanks for the Code!

anarc
Reply to this.
Anonymous at 07 Jan, 2009 03:16
How do get the results to print on the page?
Reply to this.
joe at 23 May, 2009 05:27
Binny, thanks for the code. If I just wanted to collect the file names contained in a given folder, can I merely edit your code by dropping out the lines that refer to get folder? I supposed I'd also have to specify the search folder. Do you have code stored that just searches a folder and return a list of the files names in that folder? Thanks.


Reply to this.
lemrovo at 07 Jun, 2009 07:32
I suppose there is a bug on line:

if($recursivly or $get_folders) $folders = glob("*", GLOB_ONLYDIR + GLOB_MARK);

coz if ($recursivly or $get_folders) is false then on the line:

$all = array_values(array_diff($both,$folders));

you have nothing in variable $folder and therefore in variable $all you have both files and dirs (even thought $get_folders is false).

The resolve is to load $folder every time. Means throw away the condition if($recursivly or $get_folders) and everything works fine.

This may either be the answer to the last comment.
gl lemrovo
Reply to this.
Courtney at 05 Aug, 2009 06:49
Does anyone know how to take the results of this code and "load" it into flash in an array? I've been trying to figure this out for what seems like forever. Any help would be really appreciated.
Reply to this.
Anonymous at 15 Feb, 2010 08:28
I am using the returned list of files to pass to a word indexing engine I've written.

How do I tell the function to 'exclude' certain directories/folders?

Thanks.

Peter Barganski
Reply to this.
3Djade at 19 Feb, 2010 05:19
This fucntion is cool, with it I can read the content of a folder, and use the data on the array to write an xml file and use it in Flash. Thanks for posting
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed