2

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

2
  • use glob("upload_files/*"). It returns an array of all the files in it (including folders). Too short for an answer and unchecked. Commented Jan 11, 2012 at 3:02
  • Please explain more precise what you are trying to do, and what you alredy got. some code would be nice. Commented Jan 11, 2012 at 3:03

3 Answers 3

4

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()); } 
Sign up to request clarification or add additional context in comments.

4 Comments

+1 for scandir, cause everyone else is suggesting glob for some bizarre reason
I guess they have strong Linux background
$dir = scandir($dir); will cause undefine variable
Sorry, made a typo, should be $dir = scandir($dirname); where $dirname is your upload directory
1

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!

Comments

0

The following will print all files in the folder upload_files.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.