Good afternoon, comrades.

It is necessary to display the contents of the folder using PHP, an example of an idea:

There is a path / img folder.

It is necessary that all files in the folder are displayed as follows:

<a href="/path/img/file1.jpg"><img src="/path/img/file1.jpg"/></a> <a href="/path/img/file2.jpg"><img src="/path/img/file2.jpg"/></a> 

I myself do this:

 <? $current_dir = '/home/site/public_html/pages/gallery/img/'; $dir = opendir($current_dir); while ($file = readdir($dir)) { echo "<img src=\"/path/img/$file\" width=\"250px\"/>"; } closedir($dir); ?> 

The result of my code:

 <img src="/path/img/." width="250px"> <img src="/path/img/IMG_6155.JPG" width="250px"> <img src="/path/img/.." width="250px"> 

My version with errors - from somewhere extra lines of code were added with a ".".

Please help with this task.

Thank you for attention!

    3 answers 3

    Use an iterator:

     $dir = '...'; // где ищем foreach (new DirectoryIterator($dir) as $fileInfo) { if ($fileInfo->isDot() || $fileInfo->isDir()) continue; printf( '<img src="/path/img/%s" width="250px" />%s', $fileInfo->getFilename(), PHP_EOL ); } 

    Superfluous and .. are abbreviations (correct unix experts) for the current directory and the parent directory, respectively. In my example DirectoryIterator::isDot() is responsible for their exclusion.

    Or check that the name is not equal . and .. - no others.

    • > correct the experts of unix I can not say anything about the origins, but this notation now works everywhere. - etki
    • I am confused by the word "abbreviations" - I did not find the name of these ... entities. - xEdelweiss 1:58

    You can also the good old method:

     $path = '/path/img/'; if ($open = scandir($path)) { foreach ($open as $k => $v) { if ($v != "." && $v != "..") { echo '<img src="'.$path.$v.'" width="250px">'; } } } 
    • DirecoryIterator provides much more flexibility and ease of use. And the best thing to do with this is to trim the slashes at the end of $ path and the beginning of $ v and put a slash between them. - etki

    Example

     $dir = new DirectoryIterator('common'); /** @var $file DirectoryIterator */ foreach ($dir as $file) { if($file->isFile()){ printf("%s\n", $file); } } 

    + Article where more detailed how to do it