PHP: Get list of all filenames contained within my images directory [duplicate]
I have been trying to figure out a way to list all files contained within a directory. I'm not quite good enough with php to solve it on my own so hopefully someone here can help me out.
I need a simple php script that will load all filenames contained within my images directory into an array. Any help would be greatly appreciated, thanks!
Try glob
Something like:
foreach(glob('./images/*.*') as $filename){
echo $filename;
}
scandir()
- List files and directories inside the specified path
$images = scandir("images", 1);
print_r($images);
Produces:
Array
(
[0] => apples.jpg
[1] => oranges.png
[2] => grapes.gif
[3] => ..
[4] => .
)
Either scandir()
as suggested elsewhere or
-
glob()
— Find pathnames matching a pattern
Example
$images = glob("./images/*.gif");
print_r($images);
/* outputs
Array (
[0] => 'an-image.gif'
[1] => 'another-image.gif'
)
*/
Or, to walk over the files in directory directly instead of getting an array, use
DirectoryIterator
— provides a simple interface for viewing the contents of filesystem directories
Example
foreach (new DirectoryIterator('.') as $item) {
echo $item, PHP_EOL;
}
To go into subdirectories as well, use RecursiveDirectoryIterator:
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('.'),
RecursiveIteratorIterator::SELF_FIRST
);
foreach($items as $item) {
echo $item, PHP_EOL;
}
To list just the filenames (w\out directories), remove RecursiveIteratorIterator::SELF_FIRST
You can also use the Standard PHP Library's DirectoryIterator
class, specifically the getFilename
method:
$dir = new DirectoryIterator("/path/to/images");
foreach ($dir as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
This will gives you all the files in links.
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/your_folder/";
$files = scandir($path);
$count=1;
foreach ($files as $filename)
{
if($filename=="." || $filename==".." || $filename=="download.php" || $filename=="index.php")
{
//this will not display specified files
}
else
{
echo "<label >".$count.". </label>";
echo "<a href="download.php/?filename=".$filename."">".$filename."</a>
";
$count++;
}
}
?>