To retrieve all files from a folder in PHP, including within WordPress, you can use the glob()
or scandir()
functions. Both methods are convenient and flexible for working with files.
1. Using glob()
The glob()
function returns an array of filenames and directories that match a specified pattern. Here’s an example:
$directory = '/path/to/your/directory/*'; // Path to your directory
$files = glob($directory);
foreach ($files as $file) {
if (is_file($file)) {
echo basename($file) . "<br>";
}
}
In this example:
*
represents all files in the directory.basename($file)
is used to get the filename without the full path.
2. Using scandir()
The scandir()
function returns an array of files and folders from the specified directory.
$directory = '/path/to/your/directory/';
$files = scandir($directory);
foreach ($files as $file) {
if (is_file($directory . $file)) {
echo $file . "<br>";
}
}
How to Use This in WordPress
If you are working within a WordPress theme or plugin, you can use WordPress functions to get the correct paths. For example:
$directory = get_template_directory() . '/your-folder/';
$files = scandir($directory);
foreach ($files as $file) {
if (is_file($directory . $file)) {
echo $file . "<br>";
}
}
In this example, the get_template_directory()
function is used to return the path to the current WordPress theme.
Note
- Make sure you have the correct permissions to access the folder. In WordPress, it’s often useful to use WP functions like
wp_upload_dir()
to securely access uploaded files.