- PHP list files in directories
- Write filenames from a directory to MySQL
- Order and remove files from a directory
- How to use this PHP directory and file function?
- Related Posts
- PHP: List all files in a directory.
- 4 Ways To List Files & Folders In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP GET FILES FOLDERS
- METHOD 1) SCANDIR
- 1A) BASIC SCANDIR
- 1B) SCANDIR READ SUB-FOLDERS
- METHOD 2) GLOB
- 2A) BASIC GLOB
- 2B) GLOB READ SUB-FOLDERS
- METHOD 3) OPENDIR
- 3A) BASIC OPENDIR
- 3B) OPENDIR READ SUB-FOLDERS
- METHOD 4) DIRECTORY ITERATOR
- 4A) BASIC ITERATOR
- 4B) ITERATOR READ SUB-FOLDERS
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- EXTRA) COMBINING GLOB & ITERATOR
- LINKS & REFERENCES
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
- PHP get all files in directory with extension
- Algorithm of getting all files from a folder using PHP
- Open a directory using PHP
- Read a folder using PHP
- A loop through on directory until file reading end using PHP
- Getting all files with extension
- Getting all image from a directory and display in the website with HTML tag
PHP list files in directories
PHP has some great functions to handle files withing a specified directory. The following custom functions and code examples show how to use them is real cases.
Write filenames from a directory to MySQL
This script is an example how to import all filenames from a single directory into a MySQL database table. Extra features are:
- The last modification date is stored in the database too
- All filenames that are not imported to the database are stored in an error array.
The script is very easy to use: just place the script into the folder where you want to copy the files and modify the database connection string and then run the script via the browser.
Establish a database connection
$db = new mysqli('localhost', 'username', 'password', 'databasename');
This function will open a selected directory and returns and array with all filenames.
function select_files($dir) < if (is_dir($dir)) < if ($handle = opendir($dir)) < $files = array(); while (false !== ($file = readdir($handle))) < if (is_file($dir.$file) && $file != basename($_SERVER['PHP_SELF'])) $files[] = $file; >closedir($handle); if (is_array($files)) sort($files); return $files; > > >
Next insert the filename and the modification date of the current file
function insert_record($name, $mod_date) < $sql = sprintf("INSERT INTO example SET filename = '%s', lastdate = '%s'", $name, $mod_date); if ($db->query($sql)) < return true; >else < return false; >>
Create the table structure if not exists
$db->query(" CREATE TABLE IF NOT EXISTS example ( id bigint(20) unsigned NOT NULL auto_increment, filename varchar(255) NOT NULL default '', lastdate datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (id), FULLTEXT KEY domain (filename) ) TYPE=MyISAM;");
Create the current file path
Check for the trailing slash (Windows or Linux type)
Get the filenames from the directory
$file_array = select_files($path);
Creating some controle variables and arrays
$num_files = count($file_array); $success = 0; $error_array = array();
// if the file array is not empty the loop will start
if ($num_files > 0) < foreach ($file_array as $val) < $fdate = date("Y-m-d", filectime($path.$val)); if (insert_record($val, $fdate)) < $success++; >else < $error_array[] = $val; >> echo «Copied «.$success.» van «.$num_files.» files. «; if (count($error_array) > 0) echo «\n\n
\n».print_r($error_array).»\n
«; > else
Order and remove files from a directory
Use this function to take care of the amount of files in a public map. Every time a new file is uploaded the oldest one must be removed (using the unlink() function) if a maximum limit is already reached. The second parameter is optional and will set the limit whenever the check should happen or not.
Demo: My PHP upload and download demo is using this function too.
> if (count($files) else < foreach ($files as $val) < if (is_file($directory.$val)) < $file_date[$val] = filemtime($directory.$val); >> > > closedir($handle); asort($file_date, SORT_NUMERIC); reset($file_date); $oldest = key($file_date); return $oldest; >
How to use this PHP directory and file function?
This example will show you the oldest file if there are more then 8 in the directory.
echo get_oldest_file("/path/to/your/directory/", 8);
Related Posts
PHP Ajax Whois Script Recently I’ve changed the PHP Whois demo at finalwebsites.com. I modified the default PHP whois class…
Create a select menu from files or directory This simple function generates a select element for all files of a given directory. Use…
Create a dynamic select menu with PHP In many HTML forms or content management systems the form element «SELECT» is used frequently.…
PHP: List all files in a directory.
In this beginner’s tutorial, I will show you how to list all files in a directory using PHP. We will do this using PHP’s glob function, which allows us to retrieve a list of file pathnames that match a certain pattern.
For this example, I have created a folder called “test”. Inside the folder, I have created three files:
Here is a screenshot of the directory:
In our first PHP code snippet, we will simply list everything that is in the test folder:
The result will look something like this:
test/file.php test/names.txt test/test.txt
However, what if we wanted to list all files with a particular file extension? i.e. What if we only want to list the .txt files and not the .php file that is currently present?
Well, the solution is pretty simple:
//Get a list of all files ending in .txt $fileList = glob('test/*.txt');
In the code snippet above, we told the glob function to return a list of file pathnames that ended .txt
Warning: In some cases, the folder may have subdirectories. In cases where you are listing everything that is inside a specified folder, these subdirectories will be returned by the glob function. To avoid printing out or interacting with subdirectories, you can simply use the is_file function to confirm that the file pathname in question leads to an actual file:
Hopefully, this tutorial was useful!
4 Ways To List Files & Folders In PHP (Simple Examples)
Welcome to a tutorial on how to list files and folders in PHP. So you need to get the contents of a folder in PHP? Well, be prepared for a small nasty surprise.
- foreach (scandir(«FOLDER») as $ff) < . >
- foreach (glob(«FOLDER/*») as $ff) < . >
- Open and read the folder.
- $dh = opendir(«FOLDER»);
- while ($ff = readdir($dh))
- Use an iterator.
- $it = new DirectoryIterator(«FOLDER»);
- foreach ($it as $ff)
That covers the basics, but just what is the difference? Read on for more examples!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP GET FILES FOLDERS
All right, let us now get into the examples of getting files and folders in PHP.
METHOD 1) SCANDIR
1A) BASIC SCANDIR
- file "; > if (is_dir($dir . $ff)) < echo "- folder "; > >
- scandir(«FOLDER») will give you the full list of files and folders within the specified folder in an array.
- Take note, this also includes the hidden . and .. . For those who are new, these represent the current and parent folder respectively.
- We are not interested in the “dots”, so we remove them using array_diff() .
- The rest is self-explanatory – Loop through the files and folders.
1B) SCANDIR READ SUB-FOLDERS
- file "; > if (is_dir($dir . $ff)) < echo "- folder "; rscan("$dir$ff/"); > > > // (B) GO! rscan("YOUR/FOLDER/");
If you need to “dig” into the sub-folders, create a recursive function – If the entry is a folder, pass it back into the recursive function itself.
METHOD 2) GLOB
2A) BASIC GLOB
// (A) GET FILES/FOLDERS $all = glob("YOUR/FOLDER/*"); // $all = glob("YOUR/FOLDER/*.", GLOB_BRACE); $eol = PHP_EOL; // (B) LOOP THROUGH ALL foreach ($all as $ff) < if (is_file($ff)) < echo "- file "; > if (is_dir($ff)) < echo "- folder "; > >
Now, scandir() will fetch everything. If you only need certain file types – glob() is the best option.
2B) GLOB READ SUB-FOLDERS
// (A) RECURSIVE GLOB function rglob ($dir, $ext="*") < // (A1) GET FILES $eol = PHP_EOL; foreach (glob("$dir$ext", GLOB_BRACE) as $ff) < if (is_file($ff)) < echo "- file "; > > // (A2) GET FOLDERS foreach (glob("$dir*", GLOB_ONLYDIR | GLOB_MARK) as $ff) < echo "- folder "; rglob($ff, $ext); > > // (B) GO! rglob("YOUR/FOLDER/"); // rglob("YOUR/FOLDER/", "*.");
A “recursive glob” is slightly more roundabout, but basically – Get the files first, then recursive “dig” into the folder.
METHOD 3) OPENDIR
3A) BASIC OPENDIR
- file "; > if (is_dir($ff)) < echo "- folder "; > >>
The above methods will “fetch everything into an array”. Some of you sharp code ninjas should have already caught the potential problem – What if there are thousands of files in the folder? This will run into performance and memory issues. So instead of “getting everything at once”, opendir() and readdir() will read “entry by entry”.
3B) OPENDIR READ SUB-FOLDERS
- file "; > if (is_dir($ff)) < echo "- folder "; rread("$ff/"); > >> > // (B) GO! rread("YOUR/FOLDER/");
Well, this should not be a surprise by now. Create a recursive function to open and read sub-folders.
METHOD 4) DIRECTORY ITERATOR
4A) BASIC ITERATOR
isDot()) < continue; >if ($ff->isFile()) < echo "getFilename()> - file "; > if ($ff->isDir()) < echo "getFilename()> - folder "; > >
Lastly, here is the “alternative” way to read a folder entry by entry – Using a DirectoryIterator .
4B) ITERATOR READ SUB-FOLDERS
isDot()) < continue; >if ($ff->isFile()) < echo "getFilename()> - file "; > if ($ff->isDir()) < echo "getFilename()> - folder "; riterate("getFilename()>/"); > > > // (B) GO! riterate("YOUR/FOLDER/");
Well… You guys should be masters of recursive functions by now.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
EXTRA) COMBINING GLOB & ITERATOR
// (A) GLOB ITERATOR $dir = "D:/DOCS/"; $eol = PHP_EOL; // $iterator = new ArrayObject(glob("$dir*.", GLOB_BRACE)); $iterator = new ArrayObject(glob("$dir*", GLOB_BRACE)); $iterator = $iterator->getIterator(); /* (B) OPTIONAL - PAGINATION $pgNow = 0; // current page $pgPage = 10; // entries per page $iterator = new LimitIterator($iterator, $pgNow * $pgPer, $pgPer); */ // (C) LOOP foreach ($iterator as $ff) < if (is_file($ff)) < echo "- file "; > if (is_dir($ff)) < echo "- folder "; > >
Which is the “best method”? I will say “all of them”, whichever works for you is the best. But personally, my “best solution” is a combination of glob and iterator – This is very flexible, capable of restricting by the file types, and also easily do pagination with it.
LINKS & REFERENCES
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
PHP get all files in directory with extension
Getting all files from a directory with an extension is not so hard things. In this post, we will learn how can we fetch all files from a folder in PHP.
Fetch all files or display all files in HTML tag from a folder using PHP is so easy. We just need to open the folder using PHP the «opendir()» function and then read the directory until the end using the «readdir()» function.
In this post, I will provide you the complete guideline to fetch or display all files from a folder to HTML using PHP. Also, I will provide you the source code so that you can understand it better.Algorithm of getting all files from a folder using PHP
- ✅ Open the folder using the “opendir()” function.
- ✅ Read the folder using the “readdir()” function.
- ✅ Check is it file on not.
- ✅ Read until files end.
- ✅ Understand the file type.
- ✅ Ecco with HTML tag.
Open a directory using PHP
To open a folder using PHP you need to use the “opendir()” function this function will take the location of your folder as a string and return the opened folder.
$location = "./upload"; $folder = opendir($location);
Note: here we open the ‘upload’ folder.
Read a folder using PHP
To read a folder using PHP we need to use the «readdir()» function. This function will take an opened folder. That means a folder that is already opened using PHP «opendir()» function.
Note: here we open the ‘upload’ folder.
A loop through on directory until file reading end using PHP
To loop until file read end we can use while loop, and inside the while loop’s condition, we need to use file read function.
while (false != ($files = readdir($folder))) < // now echo $file variable if it is actull file if($file != '.' && $file != '..')< // actual file path >>
Note: we know in every folder there is a single and double dot has defaulted, that’s why we need to skip through using the if condition.
Note: if your directory has multiple types of files you can check the file type just getting the extension of the file from the file path.
Getting all files with extension
$str_to_arry = explode(‘.’,$file); $extension = end($str_to_arry); if($extension == ‘jpg’)
Getting all image from a directory and display in the website with HTML tag
$location = "./upload"; $folder = opendir($location); // open folder if($folder) < $index = 0; while (false != ($image = readdir($folder))) < // read until end if($image != '.' && $image != '..')< // remove . and .. $image_path = "upload/".$image; echo '
'; // echo image with tag > > >