Page 1 of 1
"Get the contents from a directory" Question
Posted: Tue Jan 13, 2004 6:29 pm
by Grunge
http://www.evilwalrus.com/viewcode.php?codeEx=316
I love this script. I've tried many others, but this one suits my needs the best. But I do have a question if anyone would care to help me.
Is there a way I can use this script, but only pull, say, the image files? So that it would only list JPGs, GIFs, and PNGs?
Thanks for any help.
Posted: Tue Jan 13, 2004 6:51 pm
by Sarok
Well, you can use something like:
Code: Select all
<?php
// This is just a cut from the function..
function getFiles($dir = "", $sort = "type", $sortasc) {
// This can of course be optimized for your needs, and/or be declared elsewhere.
$extension_array = array(1 => 'jpg', 2 => 'gif', 3 => 'png');
global $mime;
clearstatcache();
$files = array();
$handle = @opendir($dir);
while(($file = readdir($handle)) !== false) {
if($file != "." && $file != "..") {
// Added this if statement..
if (in_array(substr(strrchr($file, "."), 1), $extension_array)) {
$files[$file]['filename'] = $file;
$files[$file]['lcfilename'] = strtolower($file);
$files[$file]['filesize'] = fileSize($dir.$file);
$files[$file]['date'] = filectime($dir.$file);
$files[$file]['type'] = substr(strrchr($file, "."), 1);
$files[$file]['size'] = filesize($dir.$file);
$files[$file]['mimetype'] = $mime[substr(strrchr($file, "."), 1)];
$files[$file]['formattedsize'] = formatSize(filesize($dir.$file));
$files[$file]['formatteddate'] = date("j/n/y G:i", filectime($dir.$file));
}
}
}
?>
This is of course only one way to do it. Im sure you will find a better method.

Posted: Tue Jan 13, 2004 6:52 pm
by Gen-ik
I don't like rippin' apart other peoples code, it takes too long and I'm bloody knackered at the moment.
However the following code might work for you. I've just put it together so I haven't tested it yet but it should do the job.
Code: Select all
<?php
function GetDirFiles()
{
$args = func_get_args();
$d = dir($args[0]);
while (false !== ($file = $d->read()))
{
if(stristr($file, "..") === false)
{
for($i=1; $i<count($args); $i++)
{
if(substr($file, -3) == $args[$i])
{
$return[] = $file;
}
}
}
}
$d->close();
if(!isset($return)) $return = false;
return $return;
}
// Get image files
$images = GetDirFiles("theFolder","gif", "jpg", "png");
// You should now have an array of image files so let's echo them.
// If there were no matching files then $images will be [b]false[/b]
if($images!== false)
{
foreach($images as $value)
echo $value."<br />";
}
else
{
echo "No matching files were found";
}
?>
To use the function simply do something like above.
The first argument is the folder name followed by any file extensions you want to look for.
Hope that helps. (hope it works)
