php內建幾個有關資料夾的函式,非常地實用與方便。而海芋最近寫程式有用到,為了避免忘記,把他寫在下面與大家一起分享。。
1.scandir:掃描資料夾的檔案,並將結果存成array。如資料夾「Test」裡面有「a.txt」和「b.txt」這兩個檔案,那麼結掃描結果會如下:
Array
(
[0] => .
[1] => ..
[2] => a.txt
[3] => b.txt
)
2.is_dir:判斷是否為資料夾的函式。
3.opendir/closedir:打開與關閉資料夾,傳回一個 resource,可供readdir使用。
4.readdir:讀取資料夾的內容。
5.chdir、getcwd:變化與得到目前指標所指的資料夾。
舉例來說,若要讀取一個資料夾內的全部檔案,並將他列印出來在螢幕上,那麼可以用以下的程式碼:
$dir = "./images";
getDirList($dir);
function getDirList($dir){
if (is_dir($dir)){
$dh = opendir($dir);
chdir ($dir);
while (($file = readdir($dh)) !== false) {
if (is_dir($file) && basename($file)!='.' && basename($file)!='..')
getDirList($file);
else if(filename($file) != "." && filename($file) != "..")
echo "current work dir:". getcwd()." ;filename: $file \n";
}
chdir("../");
closedir($dh);
}
}
function filename($file){
$path_parts = pathinfo($file);
return basename($file, $path_parts['extension']);
}