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?
答案 0 :(得分:0)
创建一个有效图像扩展名数组,如果路径信息与其中任何一个匹配,则将其添加到$documents
中。
$imageExtensions = ['jpg','png','gif']; //etc
$files = pathinfo($path);
foreach($files as $file) {
if(in_array($file['extension'], $imageExtensions) {
$documents[] = $pathInfo;
}
}
答案 1 :(得分:0)
我不信任文件名扩展名,而是使用其MIME类型。
使用finfo php函数,可以从文件中提取哑剧类型。
使用maintained list of MIME types,可以获取所有图像MIME类型,并有99%的把握确保将获取目录中的所有图像。
按照下面的代码及其注释:
// 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>';
}