0

I am moving images from xcode to an online platform and i need to generate a JSON file from a directory structure (images only) that lists the folders, and the images in those folders, with complete URL (online) AND date they where added.

I am a COMPLETE noob with PHP web stuff, so am really lost at the moment.

I found the following code, but that does not do anything so far, and does not travels into directory's.

<?php
/*
  JSON list of all images files in current directory
 */
$dir = ".";
$dh = opendir($dir);
$image_files = array();
while (($file = readdir($dh)) !== false) {
    $match = preg_match("/.*\.(jpg|png|gif|jpeg|bmp)/", $file);
    if ($match) {
        $image_files []= $file;
    }
}
echo json_encode($image_files);
closedir($dh);
?>

1 Answers1

1

The following code works for me. Found it here. I've only modified the echo, added the regex and the time. I hope this answers your question.

<?php

function getDirContents($path) {
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));

    $files = array(); 
    foreach ($rii as $file) {
        if (!$file->isDir() && preg_match("/.*\.(jpg|png|gif|jpeg|bmp)/", $file)) {
            $files[] = [
                'path' => $file->getPathname(),
                'c_time' => $file->getCTime()
            ];
        }
    }

    return $files;
}

header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'files' => getDirContents('.')
]);
Frits
  • 106
  • 1
  • 7