php列出指定目錄所有子檔案夾與檔案執行個體_PHP教程

來源:互聯網
上載者:User
php教程列出指定目錄所有子檔案夾與檔案執行個體
function listDirFiles()
{
// 設定目錄
$dirs = './';

// 申明檔案夾數組與檔案數組
$aFolders = array() ;
$aFiles = array() ;

$ocfolder = opendir( $dirs ) ;//則該函數返回一個目錄流,否則返回 false 以及一個 error。可以通過在函數名前加上 "@" 來隱藏 error 的輸出。用法opendir(path,context)


while ( $sFile = readdir( $ocfolder ) ) // readdir() 函數返回由 opendir() 開啟的目錄控制代碼中的條目 文法:readdir(dir_stream)
{
if ( $sFile != '.' && $sFile != '..' )
{
if ( is_dir( $dirs . $sFile ) ) // 判斷是否為目錄,是返回ture否就返回false;
$aFolders[] = 'dirs:' . $sFile . '
' ;
else
{
$fsize = @filesize( $dirs . $sFile ) ; //filesize() 函數返回指定檔案的大小。 文法:filesize(filename)


if ( !$fsize ) {
$fsize = 0 ;
}
if ( $fsize > 0 )
{
$fsize = round( $fsize / 1024 ) ;//round() 函數對浮點數進行四捨五入。 round(x,prec)
if ( $fsize < 1 ) $fsize = 1 ;
}

$aFiles[] = '檔案名稱:' .$sFile . '檔案大小=' . $fsize . 'KB
' ;
}
}
}


// 對目錄進行自然排序

natcasesort( $aFolders ) ;//對數組自然排序 natcasesort(array)

foreach ( $aFolders as $sFolder )
{
echo $sFolder ;
}

// 對檔案進行自然排序
natcasesort( $aFiles ) ; // 自然1-9,a-z排序natcasesort(array);
foreach ( $aFiles as $sFiles )
{
echo $sFiles ;
}


}

/*
調用方法當前有目錄
dirs:1
dirs:www.bKjia.c0m
檔案名稱:1.php
檔案名稱:2.php
*/

listDirFiles();

/*
輸出結果為
dirs:1
dirs:www.bKjia.c0m
檔案名稱:1.php檔案大小=1KB
檔案名稱:2.php檔案大小=2KB

用到函數解析
opendir
則該函數返回一個目錄流,否則返回 false 以及一個 error。可以通過在函數名前加上 "@" 來隱藏 error 的輸出。用法opendir(path,context)
is_dir
判斷是否為目錄,是返回ture否就返回false;
readdir
readdir() 函數返回由 opendir() 開啟的目錄控制代碼中的條目 文法:readdir(dir_stream)
filesize()
函數返回指定檔案的大小。 文法:filesize(filename)
natcasesort(array)
natcasesort() 函數實現了“自然排序”,即數字從 1 到 9 的排序方法,字母從 a 到 z 的排序方法,短者優先,該函數不區分大小寫。數組的索引與單元值保持關聯

http://www.bkjia.com/PHPjc/631995.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631995.htmlTechArticlephp教程列出指定目錄所有子檔案夾與檔案執行個體 function listDirFiles() { // 設定目錄 $dirs = './'; // 申明檔案夾數組與檔案數組 $aFolders= array() ; $a...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.