Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the default 'save image as' name for an image generated in PHP?

I have a page in my site, displaying some images that are produced my PHP. When I right click on an image and click Save Image As I get as default name the name of the php file used for generating the image.

This is for example the html for the image :

 <img src="picture_generator.php?image_id=5&extension=.png">

and the name I get is: picture_generator.php.png

Is there a way to set this name to a default one?

Thanks in advance

like image 713
novellino Avatar asked Jun 28 '11 14:06

novellino


3 Answers

You can provide it in the Content-Disposition HTTP header:

header('Content-Type: image/png');
header('Content-Disposition: inline; filename="' . $filename . '"');

However, some browsers (namely Internet Explorer) are likely to ignore this header. The most bullet-proof solution is to forge the URL and make the browser believe it's downloading a static file like /images/5/foo.png while the actual path behind the scenes is /picture_generator.php?image_id=5&extension=.png. This can be accomplished by some web server modules like Apache's mod_rewrite.

like image 193
Álvaro González Avatar answered Nov 12 '22 15:11

Álvaro González


You can try to set the file name using the HTTP headers but not all browsers respect that.

The simplest trick is to extend the URL so that the last part contains the desired file name:

<img src="picture_generator.php/desiredfilename.jpg?image_id=5&extension=.png&name=desiredfilename.jpg">

Note I also added the file name at the end of the query string (the name doesn't really matter) as some browsers use that part.

Depending on your server configuration this will immediately work without any special configuration (no mod_rewrite or anything like that). You can check if it works on your server by simply appending "/foo" to any PHP-URL on your site. If you see the output of your PHP, all is good. If you see a 404 error then your server configuration can't deal with such URLs.

like image 4
Udo G Avatar answered Nov 12 '22 14:11

Udo G


In your picture_generator.php file you need to add a header with the name. such as

header("Content-Disposition: attachment; filename=\"myfile.png\""); 
like image 1
BugFinder Avatar answered Nov 12 '22 14:11

BugFinder