Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing all images in a directory using PHP

Tags:

php

image

I have the code below that lists all the images in a folder, the problem is that it finds some files ( a . and a ..) that I am not sure what they are so I am not sure how to prevent them from showing up. I am on a windows XP machine, any help would be great, thanks.

Errors: Warning: rename(images/.,images/.) [function.rename]: No error in C:\wamp\www\Testing\listPhotosA.php on line 14

Warning: rename(images/..,images/..) [function.rename]: No error in C:\wamp\www\Testing\listPhotosA.php on line 14

Code:

<?php
define('IMAGEPATH', 'images/');

if (is_dir(IMAGEPATH)){
    $handle = opendir(IMAGEPATH);
}
else{
    echo 'No image directory';
}

$directoryfiles = array();
while (($file = readdir($handle)) !== false) {
    $newfile = str_replace(' ', '_', $file);
    rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
    $directoryfiles[] = $newfile;
}

foreach($directoryfiles as $directoryfile){
    if(strlen($directoryfile) > 3){
    echo '<img src="' . IMAGEPATH . $directoryfile . '" alt="' . $directoryfile . '" /> <br>';
    }
}

closedir($handle); ?>
like image 963
Drewdin Avatar asked Sep 17 '10 19:09

Drewdin


People also ask

How do I display all images in a directory in HTML?

Simply run the command from a command line window in the directory where your images are stored. If you need to have the all. html in some other place either move it there or change to >> C:\files\html\all.

How can I get a list of all the subfolders and files present in a directory using PHP?

PHP using scandir() to find folders in a directory To check if a folder or a file is in use, the function is_dir() or is_file() can be used. The scandir function is an inbuilt function that returns an array of files and directories of a specific directory.


1 Answers

I like PHP's glob function.

foreach(glob(IMAGEPATH.'*') as $filename){
    echo basename($filename) . "\n";
}
like image 103
Rocket Hazmat Avatar answered Oct 07 '22 18:10

Rocket Hazmat