How to use php to extract the whole file name in a specific folder

let's say on my web server there is a call to the upload_files folder then one of my php pages should capture the entire file name in this folder I have googled, but so far the returned file name is only the page viewed by the user thanks

+2
source share
3 answers

There are many ways to retrieve the contents of a folder, for example glob , scandir , DirectoryIterator and RecursiveDirectoryIterator , and I recommend that you check DirectoryIterator as it has great potential.

Example using the scandir method

 $dirname = getcwd(); $dir = scandir($dirname); foreach($dir as $i => $filename) { if($filename == '.' || $filename == '..') continue; var_dump($filename); } 

DirectoryIterator class example

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

The following is a less common example using the 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()); } 
+4
source

I agree with John:

 glob("upload_files/*") 

returns an array of file names.

but CAUTION! bad things can happen when you allow people to upload to your web server. backing up a script is quite difficult.

just an example: you have to make sure that no one can upload the php file to the download folder. if they can, they can then launch it by entering the appropriate URL into their browser.

please inquire about php and security before trying to do this!

+1
source

Next, all files in the upload_files folder will be printed.

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

All Articles