如何使用php检索特定文件夹中的所有文件名

如何使用php检索特定文件夹中的所有文件名

问题描述:

say, in my webserver there is a folder call upload_files then one of my php page should grab the all the file name in that folder i have googled but so far the file name returned is only the page the user browsering thanks

说,在我的网络服务器中有一个文件夹调用upload_files 然后我的一个php页面应该抓取所有文件 该文件夹中的名称 i已使用Google搜索但到目前为止返回的文件名只是用户浏览的页面 感谢 p> div>

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());
}

The following will print all files in the folder upload_files.

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

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!