我正在尝试使用php显示特定文件夹中的图像文件并尝试这样:
$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);
但我注意到我只查看jpg的小案例!如果我删除
|| strpos($file,'jpg') == false
我也查看子目录! 我的问题是:是否可能仅查看jpg,png,gif不区分大小写?
答案 0 :(得分:1)
将glob与GLOB_BRACE标志一起使用以匹配多个扩展名和括号,使其不区分大小写
$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);
答案 1 :(得分:1)
已经有内置功能。 stripos()
if (stripos($file, '.jpg') !== false || stripos($file, '.png') !== false) {
//$file should be an image
}
答案 2 :(得分:0)
只需使用glob()
,一切都很简单:
<?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);
?>
示例数组:
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
)
)