This question already has an answer here:
I'm trying to rewrite a PHP file that dynamically displays images into .jpeg in the browser so it can look like an image path.
My problem is that after introducing the rewrite rule, the images break. When I check the source code the image path is correct, but all I see is the "broken image icon".
Help is very much appreciated!
Here is the .htaccess
Options +FollowSymlinks
RewriteEngine On
RewriteRule ^images/([a-zA-Z0-9_-]+)\.jpeg$ image.php?id=$1
And here is the PHP/HTML code:
<?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>
</div>
After:
$imgname = ($_GET["id"]) . ".jpeg";
$imgpath = "images/" . $imgname;
Add:
if(file_exists($imgpath)) {
header("Content-type: image/jpeg");
readfile($imgpath);
exit;
}
header("HTTP/1.0 404 Not Found");
Don't use any HTML there - for JPEG request server should response with only header(s) and actualy image content.
You cannot serve an image with HTML content.
The following would be a minimalist version of how your script to properly deliver the image.
<?php
header('Content-Type: image/jpeg');
readfile('images/' . $_GET['id'] . '.jpeg');
Of course you can put your checks into that, but keep in mind you have to deliver another image in case of error and not a webpage.