1

I have this code that gets all the files from the directory i want. I would like to validate that i read only the images in the directory and not all the files.

$documents = [];
        $filesInFolder = \File::files('/var/www/test/storage/app/public/random_images');
        foreach ($filesInFolder as $path) {
            $documents[] = pathinfo($path);
        }
        return View::make('documents.index')->with('documents', $documents);

The pathinfo gets an array of

    array:8 [▼
  0 => array:4 [▼
    "dirname" => "/var/www/test/storage/app/public/random_images"
    "basename" => "sjsdfoltroigj.jpg"
    "extension" => "jpg"
    "filename" => "sjsdfoltroigj"
  ]
  1 => array:4 [▼
    "dirname" => "/var/www/test/storage/app/public/random_images"
    "basename" => "local-economy4pdf-pasay-city.jpg"
    "extension" => "jpg"
    "filename" => "local-economy4pdf-pasay-city"
  ]

How do i add a loop that checks all the extension in the array?

2 Answers2

0

Create an array of valid image extensions, if the path info matches any of them, then add it into $documents.

$imageExtensions = ['jpg','png','gif']; //etc

$files = pathinfo($path);

foreach($files as $file) {

  if(in_array($file['extension'], $imageExtensions) {
    $documents[] = $pathInfo;
  }

}
party-ring
  • 1,761
  • 1
  • 16
  • 38
0

I would not trust in filename extension, rather, I would use its MIME types.

Using finfo php functions, one can extract the mime type from a file.

Using a maintained list of MIME types, its possible to grab all the images MIME types and be 99% sure that you will obtain all the images in your directory.

Follow the bellow code and its comments:

// First, recover a list of mime types
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // risk of security, see: https://stackoverflow.com/a/26641565/1644937
$mimeTypes = json_decode(curl_exec($curl), true);
curl_close($curl);

// Second, get only the mime types for images (the ones that start with 'image' word)
$imagesMimeTypes = array_filter($mimeTypes, function ($key) {
    return strpos($key, 'image') === 0;
}, ARRAY_FILTER_USE_KEY);

// Third, loop through your files and check if they are images
$dir    = '/var/www/test/storage/app/public/random_images';
$files = scandir($dir);
foreach ($files as $file) {
    $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
    $fileMimeType = finfo_file($fileInfo, $dir . '\\' . $file);
    finfo_close($fileInfo);
    if (!array_key_exists($fileMimeType, $imagesMimeTypes)) {
        continue;
    }

    // The file will probably a image at this point
    echo $file;
    echo '<br>';
}
leoap
  • 1,684
  • 3
  • 24
  • 32