In this PHP tutorial, I will tell you how to read files and sub-directory from given directory with example.
Get file path and sizeIn this example, I have a folder/directory "demo" within C:\xampp\htdocs
directory.
Now using below code, You can easily get all files and their size using PHP function.
- <?php
- function getDirContents($dir, &$results = array()){
- $files = scandir($dir);
- foreach($files as $key => $value){
- $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
- if(!is_dir($path)) {
- $results[] = ['path'=>$path,'size'=>filesize($path)];
- } else if($value != "." && $value != "..") {
- getDirContents($path, $results);
- $results[] = ['path'=>$path,'size'=>filesize($path)];
- }
- }
- return $results;
- }
- $fileslist = getDirContents('C:\xampp\htdocs\demo');
- echo "<pre>";
- print_r($fileslist);
Output :
Array ( [0] => Array ( [path] => C:\xampp\htdocs\demo\file1.jpg [size] => 23708 ) [1] => Array ( [path] => C:\xampp\htdocs\demo\file2.jpg [size] => 410510 ) )
filesize
function returns the size in bytes of specified file.
In this example, I will use PHP glob()
method that returns an array of filenames or directories.
This is smarter way to find all files having specified pattern :
- <?php
- print_r(glob("*.jpg"));
- ?>
This will return all files having ".jpg" extension.
Array ( [0] => file1.jpg [1] => file2.jpg )
Using glob method you can get all the directories and files.
$dirs = array_filter(glob('*'), 'is_dir'); print_r( $dirs);
This will return the directories without files.
$fileDir = array_filter(glob('*')); print_r($fileDir);
This will return the directories with files.
Scan directory and files inside the specified path$files=scandir('C:\xampp\htdocs\demo'); print_r($files);
This will return the array of files and directory from given path.