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
3 Answers
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()); } 4 Comments
$dir = scandir($dirname); where $dirname is your upload directoryI 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!
glob("upload_files/*"). It returns an array of all the files in it (including folders). Too short for an answer and unchecked.