Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to list the files in a folder

Short answer

scandir() returns the names; remove the service entries . and ..:

<?php
 
$dir = sys_get_temp_dir() . '/recipe-list';
if (!is_dir($dir)) {
    mkdir($dir);
}
file_put_contents($dir . '/a.txt', '');
file_put_contents($dir . '/b.jpg', '');
 
echo implode(', ', array_diff(scandir($dir), ['.', '..']));

Output:

a.txt, b.jpg

Only the needed type

glob() searches by a mask and returns full paths:

<?php
 
$dir = sys_get_temp_dir() . '/recipe-list';
if (!is_dir($dir)) {
    mkdir($dir);
}
file_put_contents($dir . '/a.txt', '');
file_put_contents($dir . '/b.jpg', '');
 
echo implode(', ', array_map('basename', glob($dir . '/*.jpg')));

Output:

b.jpg

Functions used in this recipe

  • scandir — Returns the list of files and folders in a folder.
  • glob — Finds files by a name pattern.
  • is_dir — Checks whether a path is a folder.

Thanks for reading!

Donate to the site — we work hard for you.