如何创建下载链接以下载文件而不是重定向到浏览器?
问题描述:
我尝试放置一个链接以从服务器下载pdf,而不是重定向浏览器以在另一页中打开pdf.我在许多站点中都看到过这样的选项,但无法获取代码.而且大多数人说,仅使用php应该是可能的,有人可以帮我解决这个问题.
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.
答
使用以下代码将其重定向到php页面:
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();