Jump to content

[SOLVED] Dynamically changing script extension?


Mirkules

Recommended Posts

Hello all,

 

Quick question: say that I have a PHP file that generates an image using the GD libraries with a header content type set to image/png (or jpeg or whatever).

 

I have no problems displaying the image, but when a user attempts to download the image it has the extension .php. I would like the user to be able to save the file with a proper file extension (like image.jpeg).

 

Is there any way to do this? Ultimately, I also want to do this for text/plain and application/excel (this is the most important one).

 

Thanks in advance,

Mirkules

Link to comment
Share on other sites

Thanks for your reply.

 

There's not much to the code (assume the file is called image.php, and that the function imageSmoothCircle creates a smoothed circle):

$img = imageCreateTrueColor( 320, 240 );

imageSmoothCircle( $img, 160, 120, 100, array( 'R' => 0xCC, 'G' => 0x33, 'B' => 0x00 ) );
...
header( 'Content-Type: image/png' );
imagePNG( $img );
imagedestroy($img);

 

The question is how could I get the user to download this with a .png extension (for example) instead of the .php extension?

 

Thanks

Link to comment
Share on other sites

Well, to reply to my own post, I finally figured it out (from php.net):

 

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

 

To apply this to my example above, it's impossible for the user to right-click on the image and save it as a .jpeg. BUT, if I wanted to push the image, or an excel document, or a text document to the browser's save as dialog, I could use the content-disposition header.

 

Mirkules.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.