使用php下载pdf和图像文件,而不是在桌面上显示它们

时间:2014-05-09 14:27:48

标签: php download

我创建了一个仅适用于某些文件的脚本,我想改进它。 实际上,这个PHP脚本将上传的文件保存在服务器磁盘上,文件名保存在mySQL数据库中。

当我按下下载按钮时,脚本会将文件名保存到$filename,因此当我使用下面显示的代码时,我可以下载文件:

header ("Location: http://". $ _SERVER ['SERVER_NAME']. "/ FILE_DOWNLOAD /". $ filename);

问题是如果文件是图像或PDF并且我尝试从浏览器打开它,它会打开文件而不是将其下载到我的桌​​面。

我在许多论坛上寻找解决方案,但没有成功。

这是一个非常接近我正在寻找的替代方案:

$files_folder = $_SERVER['DOCUMENT_ROOT']. "/file_download/";
    if (is_file($files_folder.$filename))
    {
        $spliturl = explode (".", $filename);
        $file_extension = $spliturl[sizeof($spliturl)-1];
        switch(strtolower($file_extension)) {
              case "pdf": $ctype="application/pdf"; break;
              case "png": $ctype="image/png"; break;
              case "jpeg": $ctype="image/jpeg"; break;
              case "jpg": $ctype="image/jpeg"; break;
              default: $ctype = false; break;
        }
        if($ctype) {
            header("Content-Type: $ctype");
            header("Content-Disposition: $disposition; filename=".$filename);
            header("Content-Description: Download ");
            echo file_get_contents($files_folder.$filename);
        }echo "Error extension!";
    }else echo "The file does not exist!";

1 个答案:

答案 0 :(得分:1)

使用.htaccess或PHP标头。由于我必须仍然允许在浏览器中显示文件,但是在按钮点击下载相同的文件,我使用这个PHP代码:

if(isset($_GET['file'])){
    $path = "uploads/" . $_GET['file'];
    $filename = $_GET['file'];

    if(file_exists($path)) {
        header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
        header('Accept-Ranges: bytes');  // For download resume
        header('Content-Length: ' . filesize($path));  // File size
        header('Content-Encoding: none');
        header('Content-Type: application/pdf');  // Change this mime type if the file is not PDF
        header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
        readfile($path);  //this is necessary in order to get it to actually download the file, otherwise it will be 0Kb
    } else {
        echo "File not found on server";
    }
}else{
    echo "No file to download";
}

并调用此脚本:

www.example.com/downloadFile.php?file=someFile.pdf