Forcing browser to show file download prompt for html file – The Content-Disposition Header Field

I came across an interesting post title how to use PHP/Perl to display JavaScript. Interesting in the sense that author have displayed a nice way to dump JavaScript. I have another way of doing the same. I will simply save a JS file as a PHP file and will add some header statements on top of it and will use this PHP file as a JS source file wherever I want. This way I can take advantage of environment variable or some other setting. Its not rocket science. But header can do a lot. Look at the following example.

$examplFiles = array(
array('name'=>'an-html-doc.html', 'mimeType'=>'text/html', 'disposition'=>'inline'),
array('name'=>'an-html-doc.html', 'mimeType'=>'text/html', 'disposition'=>'attachment'),
$id = $_GET['id'];
if(isset($examplFiles[$id]) && file_exists($examplFiles[$id]['name'])){
header('Content-Type: '.$examplFiles[$id]['mimeType']);
header('Content-Disposition: '.$examplFiles[$id]['disposition'].'; filename='.$examplFiles[$id]['name']);
echo 'Error 404, file not found!';

Save this file on your LAMP stack with a name, say “a-cool-php-script.php” and access it through your browser with some id passed to it. Of course you also need to create an html file and named “an-html-doc.html” to run this script or all you will get is 404 error. For id=0 the html file will be displayed in browser and for 1 you will be presented with a file download dialog box or prompt.

Isn’t this interesting. You an use this simple code snippet to check any kind of file. All you need to know is MIME type of the file. A list of MIME types can be found here.

The example is in PHP but same will work for any web scripting language. For more read RFC 2183.