Getting the names of all files in a directory with PHP
In PHP, you can use the scandir() function to get the names of all files in a directory.
In PHP, you can use the scandir() function to get the names of all files in a directory. The function returns an array of filenames, which you can then loop through to access each file. Here is an example of how to use the scandir() function:
Example of using the scandir() function
<?php
$directory = '/path/to/directory';
if (is_dir($directory)) {
$files = scandir($directory);
foreach ($files as $file) {
echo $file . '<br>';
}
}Note: Both
scandir()andglob()include the current directory (.) and parent directory (..) entries. You may want to filter them out if you only want actual files.
Watch a video course: Learn object oriented PHP
Alternatively, you can use the glob() function.
Example of using the glob() function
<?php
foreach (glob('/path/to/directory/*') as $file) {
echo $file . '<br>';
}You can also use the opendir(), readdir(), and closedir() functions to read the contents of a directory, but scandir() is simpler and more efficient.