简体   繁体   中英

How to create download link to download a file instead of redirecting to browser?

I am trying to put a link to download a pdf from server, instead of redirecting the browser to open the pdf in another page. I have seen such options in many sites but unable to get the code. And most people says it should be possible with php only, could anyone help me for this.

Redirect it to a php page with this code:

$path_to_file = '/var/www/somefile.pdf'; //Path to file you want downloaded
$file_name = "somefile.pdf"; //Name of file for download
header('Pragma: public');   // required
header('Expires: 0');    // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Transfer-Encoding: binary');
readfile($path_to_file);
die();

or you can include this in .htaccess

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

You can sometimes change the http headers:

header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"lol.pdf\"");  

Like so. But some browsers actually prevent this for security reasons.

Edit

Since I realised it wasn't clear. These headers would be sent from another page which actually reads in the file and send it to the browser with these headers.

The link would then point it's href attribute to this PHP page which reads in the file and sends the headers.

From php

    header("Content-Type: application/octet-stream");
    header("Content-Disposition:attachment;filename=myfile.pdf");

And then the file content

Or from Apache

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM