如果有人能帮助我弄清楚浏览器无法加载图像的原因(错误 404),那就太好了。代码有效,图像源正确,但我无法弄清楚出了什么问题。(使用本地主机)
$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) == true) {
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
你在下面的陈述中有一个错误。用。不
echo '<img src="', $dir, '/', $file, '" alt="', $file, $
自
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $
和
echo 'Directory ''', $dir, ''' not found!';
自
echo 'Directory '''. $dir. ''' not found!';
这是一个可能的解决方案,解决方案#3在我对blubill答案的评论中:
yourscript.php
========================
<?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) == true)
{
$name = basename($file);
echo "<img src='img.php?name={$name}' />";
}
}
}
?>
img.php
========================
<?php
$name = $_GET['name'];
$mimes = array
(
'jpg' => 'image/jpg',
'jpeg' => 'image/jpg',
'gif' => 'image/gif',
'png' => 'image/png'
);
$ext = strtolower(end(explode('.', $name)));
$file = '/home/users/Pictures/'.$name;
header('content-type: '. $mimes[$ext]);
header('content-disposition: inline; filename="'.$name.'";');
readfile($file);
?>
您有两种方法可以做到这一点:
方法 1.安全的方式。
将图像放在/www/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);
?>