PHP将变量写入客户端下载的文件

时间:2014-08-12 05:02:05

标签: php download base64

我试图通过使用base64编码将文档上传到我的Web服务器更安全一些(除了其他一些东西)。我的最终目标是让客户端点击链接,php脚本将获取编码文件,解码,然后提示客户端下载解码文件。我可以将文件解码并存储到变量中,但似乎无法将其转换为可下载的内容。这是我到目前为止拼凑的内容,但只是将整个混乱输出到浏览器而不要求下载文件。

$getFile = file_get_contents('myDoc.pdf');
$fileDecode = base64_decode($getFile);

header('Content-Description: File Transfer');
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="finishedFile.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo $fileDecode;

2 个答案:

答案 0 :(得分:0)

尝试设置内容类型如下:

http://yogeshchaugule.com/blog/2013/how-display-pdf-browser-php

另外,请确保php文件末尾没有空行回显pdf文本。

答案 1 :(得分:0)

如果您希望用户在浏览器中执行操作,则需要JS提供一些帮助。这可能是最简单的方法,但通过ajax实现对完全不同的php文件的调用然后触发下载可能会更好。无论如何:

<?
    // check that the post params have been set
    if(isset($_GET['f'])){
        // get parameter from query string and decode the filename
        $file = base64_decode($_GET['f']);

        // return the file after checking that it exist
        if (file_exists($file)) {
            // load the files contents
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            readfile($file);
            exit;
        } else {
            $err = "Oops. That file does not exist.";
        }
    }else{
        // check for download errors
        $err = "false";
    }
?>

<html>
    <head>
        <script>
            var err = "<? echo $err; ?>";
            if(err !== "false"){
                alert(err);
            }

            function download(file){
                if (confirm('You are about to download the "'+atob(file)+'". Would you like to continue?')) {
                    var url = window.location.href.split('?')[0]+"?f="+file;
                    window.location = url;
                } else {
                    // do nothing. they said no.
                }
            }
        </script>
    </head>
    <body>
        <button onclick="download('dGVzdC5wbmc=')">Download File</button>
    </body>
</html>

这假定该文件名为test.png,但只要基数为64,就可以将其更改为任何文件。

相关问题