How to change the filename displayed in the “Save as…” dialog from .php to .png

被刻印的时光 ゝ 提交于 2019-11-30 09:28:39

问题


A simple PHP script that I picked up from stackoverflow generates a PNG with a transparent background, writes some text on it then directly outputs it to the client browser:

$font = 25;
$string = 'My Text';
$im = @imagecreatetruecolor(300, 300);
imagesavealpha($im, true);
imagealphablending($im, false);
$white = imagecolorallocatealpha($im, 255, 255, 255, 127);
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $white);
$lime = imagecolorallocate($im, 204, 255, 51);
imagettftext($im, $font, 0, 0, 30, $red, "fonts/tt0588m_.ttf", $string);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);

The scope is to obtain a simple service that feeds an image based on the parameters passed to it via URL, such as Google Charts (e.g. this QR code image).

So far, so good, except that if I click on the image generated with the code above and want to save it, the browser doesn't recognize it as being a PNG image, but a PHP script (Save as type selector has this option only), as oposed to the Google Charts example, where the resource is clearly identified as a PNG file.

How do I achieve this correct resource identification by the browser?


回答1:


Browser will use the filename from the URL as the default value in the "Save as..." dialog. You can type another name of course or save the file using the suggested name (text.php) and rename it afterwards.

You can use the Content-disposition header to "suggest" a filename to the browser. Here is an example:

header("Content-type: image/png");
header("Content-disposition: inline; filename=mytext.png");
  • inline suggests that browser should attempt to display the image. Change it to attachment to suggest that the browser should display the "Save as..." or similar dialog.
  • filename= should contain the filename of your choice.


来源:https://stackoverflow.com/questions/13181948/how-to-change-the-filename-displayed-in-the-save-as-dialog-from-php-to-pn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!