htaccess破坏了我的图像


htaccess breaks my images?

我正在尝试重写一个PHP文件,该文件在浏览器中将图像动态显示为.jpeg,使其看起来像图像路径。

我的问题是,在引入重写规则后,图像会断裂。当我检查源代码时,图像路径是正确的,但我看到的只是"损坏的图像图标"。

非常感谢您的帮助!

这是.htaccess

Options +FollowSymlinks
RewriteEngine On
RewriteRule ^images/([a-zA-Z0-9_-]+)'.jpeg$ image.php?id=$1

这里是PHP/HTML代码:

<?php
$imgname = ($_GET["id"]) . ".jpeg";
$imgpath = "images/" . $imgname; 
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php 
if (file_exists($imgpath)) {
   echo "<img src='" . $imgpath . "'" . " alt='image'></img>";
} else {
    header("HTTP/1.0 404 Not Found");
}
 ?>

</body>
</html>

您不能为图像提供HTML内容。

以下将是一个关于脚本如何正确传递图像的极简主义版本。

<?php
header('Content-Type: image/jpeg');
readfile('images/' . $_GET['id'] . '.jpeg');

当然,你可以把支票放进去,但请记住,如果出现错误,你必须提供另一张图片,而不是网页。

之后:

$imgname = ($_GET["id"]) . ".jpeg";
$imgpath = "images/" . $imgname;

添加:

if(file_exists($imgpath)) {
    header("Content-type: image/jpeg");
    readfile($imgpath);
    exit;
}
header("HTTP/1.0 404 Not Found");

不要在那里使用任何HTML-对于JPEG请求,服务器应该只响应标头和实际的图像内容。