5

I'd like to get a list of files stored in a sub directory of the /media directory in a controller.

I tried to use this one:

$dir = Mage::getBaseDir('media') . DS . $sub_dir . DS;
$files = scandir($dir);

But the array $files is empty.

I tried something like that:

$file = new Varien_Io_File();
$dir = Mage::getBaseDir('media') . DS . $sub_dir . DS;
$file->ls($dir);

Magento says Unable to list current working directory.

2 Answers 2

8

scandir should at least return the current . and parent .. directory. Make sure the directory exists and check permissions. Are you sure $files is an array at all?

When using Varien_Io_File, the correct usage would be:

$file = new Varien_Io_File();
$dir = Mage::getBaseDir('media') . DS . $sub_dir . DS;
$file->open(array('path' => $dir));
$file->ls();
3

Use DirectoryIterator, then it works. Here's my code snippet:

$dir = new DirectoryIterator(Mage::getBaseDir('media') . DS .  $sub_dir . DS . $category . DS);
$extensions = "jpg|jpeg|png";
$images = array();

foreach ($dir as $fileinfo) {
    if ($fileinfo->isFile() && stristr($extensions, $fileinfo->getExtension())) {
        array_push($images, substr($fileinfo->getPathname(),strlen($_SERVER['DOCUMENT_ROOT'])));
    }               
}

return $images;

Hope this help anyone who has the same problem :-) Maybe it's not the "magento" way, but it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.