Wednesday, November 18, 2009

PHP Force File Download

When setting up a file download on a web site you never want to link to the file directly.  By linking to the file directly you're letting the browser determine the best action to take.  If the file is capable of being opened in the browser (.txt, .jpg, .pdf) then that's what the browser will do.  However you can easily force the browser to give a download prompt.

$file = '/home/user/public_html/';

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file));
header('Connection: close');


No comments:

Post a Comment