• September 7, 2022

    There’s a lot of ways. The older way is scandir but DirectoryIterator is probably the best way.

    There’s also readdir (to be used with opendir) and glob.

    Here are some examples on how to use each one to print all the files in the current directory:

    DirectoryIterator usage: (recommended)

    foreach (new DirectoryIterator('.') as $file) {
        if($file->isDot()) continue;
        print $file->getFilename() . '<br>';
    }
    

    scandir usage:

    $files = scandir('.');
    foreach($files as $file) {
        if($file == '.' || $file == '..') continue;
        print $file . '<br>';
    }
    

    opendir and readdir usage:

    if ($handle = opendir('.')) {
        while (false !== ($file = readdir($handle))) {
            if($file == '.' || $file == '..') continue;
            print $file . '<br>';
        }
        closedir($handle);
    }
    

    glob usage:

    foreach (glob("*") as $file) {
        if($file == '.' || $file == '..') continue;
        print $file . '<br>';
    }
    

    As mentioned in the comments, glob is nice because the asterisk I used there can actually be used to do matches on the files, so glob('*.txt') would get you all the text files in the folder and glob('image_*') would get you all files that start with image_

    https://stackoverflow.com/questions/1086105/get-the-files-inside-a-directory
    https://stackoverflow.com/questions/8541180/best-way-to-get-files-from-a-dir-filtered-by-certain-extension-in-php
    https://stackoverflow.com/questions/24783862/list-all-the-files-and-folders-in-a-directory-with-php-recursive-function



เวอไนน์ไอคอร์ส

ประหยัดเวลากว่า 100 เท่า!






เวอไนน์เว็บไซต์⚡️
สร้างเว็บไซต์ ดูแลเว็บไซต์

Categories


Uncategorized