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.

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();
| improve this answer | |
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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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