用php下载文件

时间:2014-01-13 07:11:15

标签: php file path format

我想创建一个链接,使用php从服务器计算机的根目录下载excel文件。所以我写了一个简单的代码,如下所示,

   <?php

   header("Content-disposition: attachment;     filename=example.xls");

   header("Content-type: application/vnd.ms-excel");

   readfile("example.xls");

   ?>

然后可以下载但是当我想打开它时,我收到错误,说我下载的文件格式与文件扩展名指定的格式不同。我也尝试了与jpeg文件相同的方法,并没有得到相同的错误,但当我点击它,它什么也没显示。有人能帮我吗?我不太喜欢编程。提前谢谢你!

1 个答案:

答案 0 :(得分:1)

试试这个

    $file='example.xls';  $filesize=filesize($file);
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
    header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: inline; filename="'.basename($file).'"');
header("Content-Length: " . $filesize);
$fh = fopen("$file, "rb");

// output file
while(!feof($fh)) 
{
# output file without bandwidth limiting
    print(fread($fh, filesize($file))); 
}
fclose($fh);