I’m trying to dynamically rename a jpeg image file as it’s displayed to the user.
I have a file image_generate.php with the following code:
$file = $_GET['file'];
$imagepath = "path/to/image.jpg";
$image = imagecreatefromjpeg($imagepath);
header('Content-Type: image/jpeg');
$filename = "[site.com]_some_image_name_here";
header('Content-Disposition: attachment; filename="' . $filename . '.jpg"');
imagejpeg($image, NULL, 100);
imagedestroy($image); // Free up memory
And it’s called by an html image tag like so:
<img src="image_generate.php?file=imagenamehere" />
So far, the output has the following results:
- When I right-click on the image, and click “View Image,” a download dialogue pops up and asks if I’d like to save the file “[site.com]_some_image_name_here.jpg” (I want this to happen)
- If I right-click on the image, and click “Save Image As,” or “Save Image,” the filename that’s to be saved shows up as the original filename (whatever the variable $file was able to fetch).
How can I fix the second part? I’d like to modify the filename of the image even when the user clicks “Save Image As” or “Save Image.”
I DID try to change the code to this:
...
$rename = $filename . ".jpg";
imagejpeg($image, $rename, 100);
imagedestroy($image); // Free up memory
But the image fails to show up on the page with the html tag (shows up as a broken image).
I’m not very familiar with html headers and Content-Dispositions. I’m guessing there’s an error in there somewhere..?
Any ideas?
Thank you for reading!
Edit: .htaccess below
<IfModule mod_rewrite.c>
RewriteEngine On
# Sends image download request to image_generate.php for parsing
RewriteRule ^path/from/img/tag/downloads/(.*).jpg$ path/to/image_generate.php?file=$1 [NC,L]
RewriteRule ^path/to/image_generate.php$ /home/path/to/image_generate.php [NC,L]
</IfModule>
Different browsers will have different behaviors.
For example, Internet Explorer doesn’t try to fetch any header information before displaying the save file dialog when doing a
Right Click > Save Image As(It automatically assumes you want to save the result of the request, regardless of what the result is). Neither does Firefox. Therefore, for IE & Firefox, it will be impossible to specify the filename by specifying it in the headers.A more elegant and UA-compatible way of doing this would be by using Apache’s
mod_rewriteto do URL rewriting. URL rewriting allows you to reroute a request made to a URL towards another.To set this up, you need to create a
.htaccessfile in the directory whereimage_generate.phpis located containing the following:Then, simply modify your HTML to point to your rewritten URL.
This also have the advantage of making your image generation completely seamless to the user (URL wise, it looks simply like a static image).
More information about
mod_rewritecan be found here: