using symfony I'm trying to create a page listing all the images in a web folder
I created the following action :
$dir = 'images/blog';
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = @dir($fulldir) or die('Failed opening directory for reading');
while(false !== ($entry = @$d->read()))
{
$this->imagesBlog[] = array(
"file" => "/$dir/$entry",
"size" => getimagesize("$fulldir/$entry"));
$d->close();
}
And the following template :
foreach($imagesBlog as $img)
echo '<img class="photo" src="'.$img['file'].'" ' . $img['size'][3].'>'."\n";
This seems to work, but returns only one image from a folder containing multiple files.
print_r($imagesBlog):
sfOutputEscaperArrayDecorator Object
(
[count:sfOutputEscaperArrayDecorator:private] => 1
[value:protected] => Array
(
[0] => Array
(
[file] => /images/blog/FM-stupidest.png
[size] => Array
(
[0] => 300
[1] => 252
[2] => 3
[3] => 开发者_StackOverflow社区width="300" height="252"
[bits] => 8
[mime] => image/png
)
)
)
[escapingMethod:protected] => esc_specialchars
)
Help ! I'm loosing my mind here.
Wouldn't it be better to call $d->close();
outside the while loop?
I think this is the reason - after finding the first image, the resource will be closed and the next read() will fail.
For anyone else stumbling across this post while looking for the definitive answer, there is a Symfony class which takes care of this for you: sfFinder (for Symfony 1.4).
http://www.symfony-project.org/api/1_4/sfFinder
$finder = new sfFinder;
foreach($finder->in(sfConfig::get('sf_web_dir') . '/images/projects/') AS $file) {
if(is_file($file)) {
echo $file;
}
}
For Symfony 2, there is a blog post by Fabien Potencier here: http://fabien.potencier.org/article/43/find-your-files
You could use glob, it's simple enough:
$path = 'images/blog/';
$files = glob($path.'*.{jpg,gif,png}', GLOB_BRACE);
精彩评论