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;

Magento says Unable to list current working directory.

2 Answers 2


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));

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 that you have read and understand our privacy policy and code of conduct.

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