PHP使用标题输出文件附件

[英]PHP Outputting File Attachments with Headers


After reading a few posts here I formulated this function which is sort of a mishmash of a bunch of others:

在这里阅读了几篇文章后,我制定了这个函数,这是一堆其他的混合:

function outputFile( $filePath, $fileName, $mimeType = '' ) {
    // Setup
    $mimeTypes = array(
        'pdf' => 'application/pdf',
        'txt' => 'text/plain',
        'html' => 'text/html',
        'exe' => 'application/octet-stream',
        'zip' => 'application/zip',
        'doc' => 'application/msword',
        'xls' => 'application/vnd.ms-excel',
        'ppt' => 'application/vnd.ms-powerpoint',
        'gif' => 'image/gif',
        'png' => 'image/png',
        'jpeg' => 'image/jpg',
        'jpg' => 'image/jpg',
        'php' => 'text/plain'
    );

    // Send Headers
    //-- next line fixed as per suggestion --
    header('Content-Type: ' . $mimeTypes[$mimeType]); 
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    header('Cache-Control: private');
    header('Pragma: private');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    readfile($filePath);

}

I have a php page (file.php) which does something like this (lots of other code stripped out):

我有一个php页面(file.php),它做了这样的事情(许多其他代码被剥离):

   // I run this thru a safe function not shown here
$safe_filename = $_GET['filename']; 
outputFile ( "/the/file/path/{$safe_filename}", 
             $safe_filename, 
             substr($safe_filename, -3) );

Seems like it should work, and it almost does, but I am having the following issues:

好像它应该工作,它几乎可以,但我有以下问题:

  1. When its a text file, I am getting a strange symbol as the first letter in the text document

    当它是一个文本文件时,我得到一个奇怪的符号作为文本文档中的第一个字母

  2. When its a word doc, it is corrupt (presumably that same first bit or byte throwing things off).

    当它是一个单词doc时,它是腐败的(可能是相同的第一位或字节丢弃了)。

  3. I presume all other file types will be corrupt - have not even tried them

    我认为所有其他文件类型都将被破坏 - 甚至没有尝试过它们

Any ideas on what I am doing wrong?

关于我做错的任何想法?

Thanks -

UPDATE: changed line of code as suggested - still same issue.

更新:根据建议改变了代码行 - 仍然是同一个问题。

2 个解决方案

#1


Ok, I figured it out.

好的,我明白了。

The script above DOES work.

上面的脚本可以工作。

What was happening is I had a series of include_once files, and one of them had a blank line causing the issue.

发生的事情是我有一系列include_once文件,其中一个有一个空行导致问题。

#2


Not sure if this is the real answer, but I think you intended

不确定这是否真的答案,但我认为你的意图

header('Content-Type: ' . $mimeType);

to be

header('Content-Type: ' . $mimeTypes[$mimeType]);

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/05/22/2fa979157dacd9f338c3cd9b3f339051.html



 
  © 2014-2022 ITdaan.com 联系我们: