[PHP] Simple File Directory Scanner
I've been wanting to do one of these for some time as I find them very handy.
Basically, this function I've created allows you to get files from any directory on your webserver.
The code can be found below:
PHP Code:
<?php
function GetFiles( $directory, $output_array = false, $exts = array( "png", "jpeg", "jpg", "bmp", "gif" ) )
{
if ( is_dir( $directory ) )
{
$scan = scandir( $directory );
$return = array();
foreach( $scan as $file )
{
$ext = strtolower( end( explode( ".", $file ) ) );
if ( $file !== "." && $file !== ".." & in_array( $ext, $exts ) == true )
{
if ( $output_array == true )
{
$return[] = $file;
}
else
{
echo $file . "<br />";
}
}
}
if ( $output_array == true ) return $return;
}
else
{
echo "Directory {$directory} is invalid!";
}
}
GetFiles( "images/work" );
?>
The code above will return something similar to this:
PHP Code:
<?php
function GetFiles( $directory, $output_array = false, $exts = array( "png", "jpeg", "jpg", "bmp", "gif" ) )
{
if ( is_dir( $directory ) )
{
$scan = scandir( $directory );
$return = array();
foreach( $scan as $file )
{
$ext = strtolower( end( explode( ".", $file ) ) );
if ( $file !== "." && $file !== ".." & in_array( $ext, $exts ) == true )
{
if ( $output_array == true )
{
$return[] = $file;
}
else
{
echo $file . "<br />";
}
}
}
if ( $output_array == true ) return $return;
}
else
{
echo "Directory {$directory} is invalid!";
}
}
echo "<pre>";
print_r ( GetFiles( "images/work", true ) );
echo "</pre>";
?>
The code above will return something similar to:
You can make the function return an array by adding ", true" after your directory.
Hope this script helps.
m0nsta.
Re: [PHP] Simple File Directory Scanner
#thread moved to correct section.
Re: [PHP] Simple File Directory Scanner
Stop using echo. There is a reason we return error codes in PHP. The statement:
PHP Code:
if ( $file !== "." && $file !== ".." & in_array( $ext, $exts ) == true )
is redundant. If $ext exists in $exts, it will never be "." or ".." Rather than using an O(n) method like in_array(), create an array with file extension keys and boolean values, or something of the sort to force the array to behave as a hash map.
Re: [PHP] Simple File Directory Scanner