Is there a quick inline way, to make some of my links prompt 'save file as' (Same screen as right click) after the first initial click?
Asked
Active
Viewed 975 times
0
-
possible duplicate of [open download dialog with php](http://stackoverflow.com/questions/985083/open-download-dialog-with-php) – mario Dec 06 '11 at 13:56
-
Not really a duplicate because the question doesn't directly ask how to do it using server-side. Therefore the answer needs to explain that it cannot be done client-side and therefore server side approach is needed. – Gajus Dec 06 '11 at 14:00
2 Answers
2
You simply need to send appropriate headers. Content-Disposition
is the key (see http://en.wikipedia.org/wiki/MIME).
See PHP example below.
/**
* @author Gajus Kuizinas <g.kuizinas@anuary.com>
* @copyright Anuary Ltd, http://anuary.com
* @version 1.0.1 (2011 11 18)
*/
function ay_file_force_download($file, $file_name = NULL)
{
if(headers_sent())
{
throw new Ay_Exception('Headers have been already sent. Cannot force file download.');
}
$file_name = $file_name === NULL ? basename($file) : $file_name;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $file_name);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

Gajus
- 69,002
- 70
- 275
- 438
-
Oh - But, wouldn't that apply to all my links? I just wanted to do this with certain links? - possible? – Dr Upvote Dec 06 '11 at 14:01
0
What you really need on the php side is to set the Content-Disposition
header, to attachment, as in header('Content-Disposition: attachment; filename=name-of-file');
. If you have to or want to do it on the client side, browsers will automatically attempt to download a lot of document types, so you can just provide a straight link to it. Apparently this is not happening for you, though, so of course it's not dependable.

Explosion Pills
- 188,624
- 52
- 326
- 405