How to set the default value for “Save Image As” for an image generated in PHP?

I have a page on my site displaying some images that are created in my PHP. When I right-click on the image and click "Save Image", I get the default name of the php file used to generate 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: picture_generator.php.png

Is there any way to set this name by default?

Thanks in advance

+8
php image
source share
3 answers

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

The easiest 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 line (the value of name really doesn't matter), as some browsers use this part.

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

+4
source share

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

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

However, some browsers (namely Internet Explorer) probably ignore this header. The most bulletproof solution is to fake the url and make the browser believe that it is loading a static file like /images/5/foo.png and the actual path backstage is /picture_generator.php?image_id=5&extension=.png . This can be accomplished with some web server modules, such as Apache mod_rewrite .

+9
source share

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

 header("Content-Disposition: attachment; filename=\"myfile.png\""); 
+1
source share

All Articles