I'm trying to show only images files from a specific folder with php and try so:
$dirname = "users/".trim($_GET['nome']);
$files = array();
if (is_dir($dirname)) {} else {mkdir($dirname, 0777);}
$dir = opendir($dirname);
//while ($file = readdir($dir)) {
while ($file = readdir($dir)) {
//if ($file == '.' || $file == '..') {
if($file == '.' || $file == '..' || strpos($file,'jpg') == false){
continue;
}
$files[] = array('file' => 'http://www.lavorirapidi.it/public/users/'.trim($_GET['nome']).'/'.$file, 'name' => $file);
}
echo json_encode($files);
But I notice that I view only jpg small case! If I remove
|| strpos($file,'jpg') == false
I view also subdirectory! My question is: is it possible view only jpg, png, gif not case sensitive?
Use glob with the GLOB_BRACE flag to match multiple extension and bracket to make it case insensitive
$dirname = "users/".trim($_GET['nome']);
$files = array();
if (is_dir($dirname)) {} else {mkdir($dirname, 0777);}
$fileNames = glob("*.{[jJ][pP][gG],[pP][nN][gG],[gG][iI][fF]}", GLOB_BRACE);
foreach($fileNames as $fileName){
$files[] = array('file' => 'http://www.lavorirapidi.it/public/users/'.trim($_GET['nome']).'/'.$fileName, 'name' => $fileName);
}
echo json_encode($files);
There's already a built in function for that. stripos()
if (stripos($file, '.jpg') !== false || stripos($file, '.png') !== false) {
//$file should be an image
}
Just use glob()
and everything is that easy:
<?php
$dirname = "users/" . trim($_GET['nome']);
if (!is_dir($dirname))
mkdir($dirname, 0777);
$files = glob($dirname . "/*.*");
//filter all non images out of the files array
$files = array_filter($files, function($v){
return in_array(strtolower(pathinfo($v)["extension"]), ["jpg", "png", "gif"]);
});
//modify array to expected output
$files = array_map(function($v){
return ["file" => "http://www.lavorirapidi.it/public/users/" . trim($_GET['nome']) . "/" . $v, "name" => $v];
}, $files);
echo json_encode($files);
?>
Example array:
Array
(
[0] => Array
(
[file] => http://www.lavorirapidi.it/public/users/test/test/1.Jpg
[name] => test/1.Jpg
)
[1] => Array
(
[file] => http://www.lavorirapidi.it/public/users/test/test/2.JPG
[name] => test/2.JPG
)
[2] => Array
(
[file] => http://www.lavorirapidi.it/public/users/test/test/3.pNg
[name] => test/3.pNg
)
[3] => Array
(
[file] => http://www.lavorirapidi.it/public/users/test/test/4.jpG
[name] => test/4.jpG
)
)
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.