1. 程式人生 > >php遍歷資料夾、檔案

php遍歷資料夾、檔案

php遍歷資料夾、檔案

<?php
$path = '/';
foreach_file($path);//傳入需要遍歷的資料夾路徑

function foreach_file($path)
{
    if(is_dir($path))//判斷目錄是否存在
    {
        //opendir()返回一個目錄控制代碼,失敗返回false
        if($current_dir = opendir($path))
        {
            //讀取目錄控制代碼裡的每一個檔案,讀到最後會返回false
            while(($file = readdir($current_dir
)) !== false) { $sub_dir = $path . DIRECTORY_SEPARATOR . $file;//拼接檔案路徑 if($file == '.' || $file == '..')//判斷是否是..和.,如果是則continue { continue; } else if(is_dir($sub_dir))//判斷是不是資料夾,如果是則遞迴進入該資料夾 { foreach_file($sub_dir
); } else { //這裡讀到檔案,做相應的處理 echo 'File in Directory ' . $path . ': ' . $file . '<br>'; } } } } } ?>