1

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] => width="300" height="252"
                            [bits] => 8
                            [mime] => image/png
                        )

                )

        )

    [escapingMethod:protected] => esc_specialchars
)

Help ! I'm loosing my mind here.

Manu
  • 4,410
  • 6
  • 43
  • 77
  • 1
    This is at least a quadruplicate. Please find your answer in http://stackoverflow.com/search?q=list+all+files+in+a+directory+php – Gordon Jan 21 '11 at 13:58
  • possible duplicate of [PHP list all files in directory](http://stackoverflow.com/questions/3826963/php-list-all-files-in-directory) – Gordon Jan 21 '11 at 13:58
  • And since you are using Symfony, you might also be interested in http://fabien.potencier.org/article/43/find-your-files – Gordon Jan 21 '11 at 13:59
  • Well I thought the fact I am using Symfony might have something to do with my problem – Manu Jan 21 '11 at 14:03

3 Answers3

6

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.

2

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

nealio82
  • 2,611
  • 1
  • 17
  • 19
1

You could use glob, it's simple enough:

$path = 'images/blog/';
$files = glob($path.'*.{jpg,gif,png}', GLOB_BRACE);
netcoder
  • 66,435
  • 19
  • 125
  • 142