How can PHP loop through files in a folder?

You can use the scandir function in PHP to loop through the files in a folder. Here is a simple example code:

$dir = '/path/to/directory'; // 文件夹路径

// 扫描文件夹并返回文件名数组
$files = scandir($dir);

// 循环遍历文件数组
foreach ($files as $file) {
    // 忽略当前目录和上一级目录
    if ($file == '.' || $file == '..') {
        continue;
    }

    // 输出文件名
    echo $file . "\n";
}

In the given example, the scandir function is first used to scan a specified folder, then loop through the returned array of file names, excluding the current directory “.” and the parent directory “..”, and outputting the file names. You can further process these files as needed, such as reading the file contents or other operations.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds