Sometimes you need the browser to download a resource – like an image or a pdf file – but instead of poping up the “Save link as” window, the browser opens the content in a new window. The reason why this happens is quite simple: the browser receives a header from the server containing the file’s MIME type. The browser then checks to see if it has a handler for that MIME type and if it does, it displays the content in a window, using the handler to parse the data. If it doesn’t find any suitable handler, the browser opens the download dialog. That’s why, by default, when you click on a pdf, the browser opens the download dialog, but if you install Adobe’s Reader, then the pdf is open within a browser window, because now the browser “knows” how to interpret pdf data.
If you want the browser to always download a file, you must send that file to the browser as binary data, with no specific MIME type. The php snippet below does just that.
/**
* forces the browser to download a file rather than open it
* very useful if you want to download images
*/
if ( !file_exists( $url ) )
{
header( 'HTTP/1.0 404 Not Found' );
die();
}
session_cache_limiter( 'none' );
@ set_time_limit( 0 );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0');
header( 'Content-Description: File Transfer');
header( 'Content-Type: application/octet-stream');
header( 'Content-Length: ' . filesize( $url ) );
header( 'Content-Disposition: attachment; filename=' . basename( $url ) );
readfile( $url );
Enjoy!