Im trying to scan multiple image directories using PHP and create an array that contains the exact path of each image and its name.
Example directory tree
main/
├─ sub-directory-1/
│ ├─ image1.png
│ ├─ image2.jpeg
│ ├─ image3.png
├─ sub-directory-2/
│ ├─ image1.png
├─ sub-directory-3/
│ ├─ image1.jpeg
│ ├─ imageX.png
Example of desired array
{
0 : {name: "image1", path: "main/subdirectory-1/image1.png"},
1 : {name: "image2", path: "main/subdirectory-1/image2.jpeg"},
2 : {name: "image3", path: "main/subdirectory-1/image3.png"},
.
.
.
7 : {name: "imageX", path: "main/subdirectory-3/imageX.png"},
}
This is the approach that got me the desired result.
I hope this will help someone
public function ImageScanner() {
$current_dir = getcwd();
$folderpath = 'PATH/TO/SOME/DIR/';
// Determining if the path is a directory or not
if (is_dir($folderpath)) {
// Opening the directory
$files = opendir($folderpath); {
// Checking if the directory opened
if ($files) {
//Reading each element's name in the directory
while (($subfolder = readdir($files)) !== false) {
// Checking for errors in filename
if ($subfolder != '.' && $subfolder != '..') {
$dirpath = 'SOME/SUB_DIR/PATH/' . $subfolder . '/';
// Checking and opening each file inside the sub directory
if (is_dir($dirpath)) {
$file = opendir($dirpath);
if ($file) {
// Reading each element's name in the sub directory
while (($filename = readdir($file)) !== false) {
if ($filename != '.' && $filename != '..') {
$image_path = '' . $dirpath . '' . $filename . '';
// Creating array for each scanned file
$key = array(
'image_name' => trim($filename) ,
'image_path' => str_replace('/SOME/PATH/', '', $image_path) ,
);
// Appending each image array
$image_arrays[] = $key;
}
}
}
}
}
}
}
}
}
return $image_arrays;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.