显示存储在服务器中的pdf文件并使用php下载

时间:2012-09-18 06:57:20

标签: php file filesystems download

我已将.pdf,.doc,.txt文件存储在Web服务器的目录中。我能够显示存储在目录中的所有文件,但下载失败。每次我点击超链接sample.txt下载空白内容。请查看代码并建议我。

这就是我在show_directory.php中使用的

<?PHP
    // Define the full path to your folder from root 
    $path = "/public_html/bc/upload/"; 

    // Open the folder 
    $dir_handle = @opendir($path) or die("Unable to open $path"); 

    // Loop through the files 
    while ($file = readdir($dir_handle)) { 

    if($file == "." || $file == ".." || $file == "download_file.php" ) 

        continue; 
        echo "<a href=\"download_file.php\">$file</a><br />"; 


    } 
    // Close 
    closedir($dir_handle); 
?>

download_file.php的内容是:

<?PHP
//download.php
//content type
header('Content-type: text/plain');
//open/save dialog box
header('Content-Disposition: attachment; filename="sample.txt"');
//read from server and write to buffer
readfile('test.txt');
?>

1 个答案:

答案 0 :(得分:0)

....
header('Content-Description: File Transfer');
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . 'test.txt' . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile('test.txt');
....

为什么不使用二进制文件?