有两种方式做到这一点:
方法1.安全的方式。
把图像上/网络/ htdocs中/
<?php
$www_root = 'http://localhost/images';
$dir = '/var/www/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))) {
echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
break;
}
}
}
?>
方法2不安全,但更灵活。
将图像放在任何目录(apache必须有权限读取文件)。
<?php
$dir = '/home/user/Pictures';
$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))) {
echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
break;
}
}
}
?>
并创建另一个脚本来读取图像文件。
<?php
$filename = base64_decode($_GET['file']);
// Check the folder location to avoid exploit
if (dirname($filename) == '/home/user/Pictures')
echo file_get_contents($filename);
?>
那么你为什么不张贴代码? –
刚刚做到了。忘了缩进。 – user2837048
上面的代码存在语法错误,比如in_array(没有右括号,有人需要学习基本语法 – jerjer