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

I am trying to put a link to download a pdf file from the server, instead of redirecting the browser to open the pdf file on another page. I saw such options on many sites, but could not get the code. And most people say this should only be possible with php, can anyone help me with this.

+4
source share
4 answers

Redirect it to 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(); 
+5
source

or you can include this in .htaccess

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

Sometimes you can change the http headers:

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

Same. But some browsers actually prevent this for security reasons.

Edit

Since I realized that this is not clear. These headers will be sent from another page that is actually read in the file and sends it to the browser with these headers.

The link then points to the href attribute on this PHP page, which reads in the file and sends the headers.

0
source

From php

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

And then the contents of the file

Or from Apache

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

Source: https://habr.com/ru/post/1435920/


All Articles