How do I write a link in HTML/PHP that makes the user download a file?
I am writing a program in PHP that uses file uploading and file downloading. The one problem is that the files can be any type, and开发者_如何学编程 I don't know how to make it so that the link makes a download popup appear. How do I do this?
Thanks!
Nerd With a Vengeance
So to help put this all together for you.
Page 1 (User selects a file to download)
files_to_download.php (file that user sees)
<a href="download.php?file=file1.pdf">PDF File</a>
<a href="download.php?file=file1.doc">Word Doc File</a>
<a href="download.php?file=file1.ppt">Power Point File</a>
download.php (file that is linked to)
<?php
$file = $_GET['file'];
// set your path
$path = '/path/to/your/files/';
// you'd probably want to do some error check here
// e.g. does file exist, etc.
// start download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
If you put
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="blah.dat');
into the PHP file that serves the download, the browser will always open a download window, even for files it could handle by itself.
Setting the appropriate content disposition should work:
header('Content-Disposition: attachment');
You need to do this in the PHP script which sends the file contents. If the files are static and not served via PHP you can also do it using a .htaccess file (when using Apache):
Header set Content-Disposition attachment
精彩评论