本文實例總結了PHP目錄操作方法。分享給大家供大家參考,具體如下:
目錄操作
新建目錄:mkdir(路徑,權限,遞歸創建)
刪除目錄:rmdir()
移動(改名):rename()
獲取目錄內容:
//打開目錄
目錄句柄 = opendir()
//讀取目錄
文件名 = readdir(目錄句柄)
依次讀取文件名,同時向下移動文件句柄指針,讀取不到則返回false
//關閉目錄
closedir()
遞歸讀取目錄內容:
<?php
showDir('../../file');
function showDir($path,$dep=0){
$pos = opendir($path);
while(false!==$file=readdir($pos)){
if($file=='.'||$file=='..') continue;
echo str_repeat(" ",$dep*4),$file.'</br>';
if(is_dir($path.'/'.$file)){
$func = __FUNCTION__;
$func($path.'/'.$file,$dep+1);
}
}
}
運行效果圖如下:

<?php
$res = showDir('../../file');
echo '<pre>';
print_r($res);
function showDir($path){
$pos = opendir($path);
$next = array();
while(false!==$file=readdir($pos)){
if($file=='.'||$file=='..') continue;
$fileinfo = array();
$fileinfo['name'] = $file;
if(is_dir($path.'/'.$file)){
$fileinfo['type'] = 'dir';
$func = __FUNCTION__;
$fileinfo['next'] = $func($path.'/'.$file);
}else{
$fileinfo['type'] = 'file';
}
$next[] = $fileinfo;
}
closedir($pos);
return $next;
}
運行效果圖如下:

遞歸刪除目錄:
<?php
showDir('../../file/sim');
function showDir($path,$dep=0){
$pos = opendir($path);
while(false!==$file=readdir($pos)){
if($file=='.'||$file=='..') continue;
// echo str_repeat(" ",$dep*4),$file.'</br>';
if(is_dir($path.'/'.$file)){
$func = __FUNCTION__;
$func($path.'/'.$file,$dep+1);
}else{
unlink($path.'/'.$file);
}
}
rmdir($path);
closedir($pos);
}
目錄文件編碼問題:
展示時,將操作系統編碼轉換為響應數據編碼
windows為gbk,項目 utf-8
iconv('gbk',utf-8',file);
代碼地址存在中文:需要轉換為系統編碼
iconv(utf-8','gbk',file);
更多關於PHP相關內容感興趣的讀者可查看本站專題:《PHP目錄操作技巧匯總》、《php文件操作總結》、《PHP數組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php面向對象程序設計入門教程》、《PHP網絡編程技巧總結》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。