使用 PHP 显示服务器上存在的图像


Display images present on server using PHP

我需要从服务器上存在的文件夹中在网页上显示图像。我试过这个:

$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');

if (file_exists($dir) ==false) {
echo 'Directory ''', $dir, ''' not found';
} else {
$dir_contents = scandir($dir);

foreach ($dir_contents as $file) {
    $file_type = strtolower(end(explode('.', $file)));
    if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
    echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
    }
}
}

它不起作用,所以我做了一些更改并尝试了这个:

$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');

if (file_exists($dir) ==false) {
echo 'Directory '''. $dir. ''' not found';
} else {
$dir_contents = scandir($dir);

foreach ($dir_contents as $file) {
    $file_type = strtolower(end(explode('.', $file)));  ''ERROR
    if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
    echo '<img class="photo" src="'. $dir. '/'. $file. '" alt="'. $file. '" />';
    }
}
}

但是有一个错误"只有变量应该通过引用传递",所以我尝试了:

$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');

if (file_exists($dir) ==false) {
echo 'Directory ''', $dir, ''' not found';
} else {
$dir_contents = scandir($dir);

foreach ($dir_contents as $file) {
    $file_type = strtolower(end(explode('.', $file)));
     $tmp = explode('.', $file);   ''CHANGED THIS LINE
     $file_type = end($tmp);  ''CHANGED THIS LINE
    if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
    echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
    }
}
}

任何想法如何使用PHP动态显示服务器上存在的图像?

在我的一个项目中,我使用了RecursiveDirectoryIterator和RegexIterator,它将处理图像目录中的多个文件夹并创建一个有效文件数组(与正则表达式匹配,在我们的例子中是扩展名为jpg|jpeg|png|gif的文件)

<?php
$folder = 'images';
try {
    $directory = new RecursiveDirectoryIterator(realpath($folder));
    $iterator = new RecursiveIteratorIterator($directory);
    $files = new RegexIterator($iterator, '/^.+'.(jpg|jpeg|png|gif)$/i', RecursiveRegexIterator::GET_MATCH);
} catch (Exception $e) {
    echo "Invalid Directory: ".$e->getMessage();
}
//$files is an array with file name of all the valid images
if(isset($files) && $files != null){
    foreach($files as $filepath => $value){
        echo "<img src='".$filepath."'><br>";
    }
}
?>

希望这有帮助