php之readdir函數用法執行個體_php技巧

來源:互聯網
上載者:User

本文執行個體講述了php中readdir函數用法。分享給大家供大家參考。具體用法分析如下:

定義和用法:readdir() 函數返回由 opendir() 開啟的目錄控制代碼中的條目,若成功,則該函數返回一個檔案名稱,否則返回 false.

執行個體一,代碼如下:

複製代碼 代碼如下:
$dir = "readdir/";
 
// 判斷是否為目錄
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . " ";
        }
        closedir($dh);
    }
}

執行個體二,注意在 4.0.0-RC2 之前不存在 !== 運算子,代碼如下:
複製代碼 代碼如下:
if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle ";
    echo "Files: ";
 
    /* 這是正確地遍曆目錄方法 */
    while (false !== ($file = readdir($handle))) {
        echo "$file ";
    }
 
    /* 這是錯誤地遍曆目錄的方法 */
    while ($file = readdir($handle)) {
        echo "$file ";
    }
    closedir($handle);
}

執行個體三,readdir() 將會返回 . 和 .. 條目,如果不想要它們,只要過濾掉即可,例子 2. 列出目前的目錄的所有檔案並去掉 . 和 ..,代碼如下:
複製代碼 代碼如下:
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file ";
        }
    }
    closedir($handle);
}

注: readdir必須與opendir配合使用才行.

希望本文所述對大家的php程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.