get files of a directory
-
12-12-2019 - |
Question
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.
Solution
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();
OTHER TIPS
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
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange