PHP:点击按钮下载文件?

时间:2013-03-01 11:32:46

标签: php download

我创建了一个表单,当单击一个包含的按钮时,应该打开一个下载对话框来下载某个文件。该文件放在同一台服务器上。

我试过了:

header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=" . $file . '"'); 

其中$ file是本地路径+文件名,例如c:\ mypath \ myfile.xls。但这不起作用。它提供了一个文件,但它不是一个有效的文件。我怎么能这样做?

注意:我写了c:\因为它仍然在我的本地机器上进行测试。

谢谢!

4 个答案:

答案 0 :(得分:3)

试试这个

header("Pragma: public", true);
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
die(file_get_contents($file));

我认为file_get_contents()函数不再适用于PHP 5.0.3

答案 1 :(得分:1)

试试这个:

$path = "http://www.example.com/files/";
$filename = "abc.gif";

header("Content-Type:image/gif");
header("Content-Disposition: attachment; filename=".$filename);
header("Cache-control: private");
header('X-Sendfile: '.$path);
readfile($path);
exit;

答案 2 :(得分:0)

PHP在服务器端运行,你无法在客户端机器上下载文件。

将文件上传到服务器,然后提供该路径进行下载。

答案 3 :(得分:0)

必须从站点根目录引用路径...移动文件 例如: 脚本路径:C:/wamp/www/test.php 文件C:/script.js 然后:

if(file_exists('../../user.js'))
{
    echo "OK";
}

还是个坏主意......

相关问题