简体   繁体   中英

How to use php to retrieve all the file name in a specific folder

说,在我的网络服务器上,有一个文件夹调用upload_files,那么我的php页面之一应该抓住我在Google上搜索过的那个文件夹中的所有文件名,但到目前为止,返回的文件名只是用户浏览的页面谢谢

There are many ways of retrieving folder content like glob , scandir , DirectoryIterator and RecursiveDirectoryIterator , personaly I would recommend you to check DirectoryIterator as it has big potential.

Example using scandir method

$dirname = getcwd();

$dir = scandir($dirname);

foreach($dir as $i => $filename)
{
    if($filename == '.' || $filename == '..')
        continue;

    var_dump($filename);
}

Example using DirectoryIterator class

$dirname = getcwd();

$dir = new DirectoryIterator($dirname);

foreach ($dir as $path => $splFileInfo)
{
    if ($splFileInfo->isDir())
        continue;

    // do what you have to do with your files

    //example: get filename
    var_dump($splFileInfo->getFilename());
}

Here is less common example using RecursiveDirectoryIterator class:

//use current working directory, can be changed to directory of your choice
$dirname = getcwd();

$splDirectoryIterator = new RecursiveDirectoryIterator($dirname);

$splIterator = new RecursiveIteratorIterator(
    $splDirectoryIterator, RecursiveIteratorIterator::SELF_FIRST
);

foreach ($splIterator as $path => $splFileInfo)
{
    if ($splFileInfo->isDir())
        continue;

    // do what you have to do with your files

    //example: get filename
    var_dump($splFileInfo->getFilename());
}

I agree with Jon:

glob("upload_files/*")

returns an array of the filenames.

but BEWARE! bad things can happen when you let people upload stuff to your web server. building a save uploading script is quite hard.

just an example: you have to make sure that nobody can upload a php-file to your upload-folder. if they can, they can then run it by entering the appropriate url in their browser.

please learn about php & security before you attempt to do this!

The following will print all files in the folder upload_files .

$files = glob("upload_files/*");
foreach ($files as $file)
    print $file;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM