Manual setting of filename and type in a dynamically-generated web page

Problem: Suppose you have a CGI script (PHP or otherwise), say genimage.cgi, that generates an image and sends it to the browser. If the user visits the URL of the script and tries to save the generated image, the browser might suggest “genimage.cgi” as the default filename to save to, which might lead to confusion (e.g. the OS won’t associate an image-viewing action with the file).

Solution: Have the script tell the browser the filename that it should use if the user wants to save the page. This can be done by sending a HTTP response header. Suppose the filename should be “image.gif”, then send the following header:

Content-Disposition: inline; filename=image.gif

Your script might also want to manually set the MIME type of the resulting page. If it doesn’t, either the web server or the browser might try to make a guess, which might be wrong. For exmple, you can set the MIME type to that of a GIF image by sending the following HTTP response header:

Content-Type: image/gif

Here is the code for sending both headers in PHP:


// Suppose you want to send a GIF file to the browser

// Send the headers first

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

// Then print the content of the GIF file

// e.g.
// print file_get_contents('some_gif_file.gif');