PHP - 将文件发送给用户

Ian*_*gan 44 php

我在磁盘上有一个pdf文件,当他们向php脚本发出请求时,我需要发送给用户,这样做的最佳方法是什么?

谢谢

Adi*_*ael 55

假设它在服务器上:

readfile() - 输出文件

来自http://php.net/manual/en/function.readfile.php的示例

  • 该示例包含大量垃圾.HTTP中不存在Content-Description.Content-Type应设置为实际媒体类型,或者根本不设置.Content-Disposition的代码将为许多文件名生成不正确的标头.HTTP中不存在Content-Transfer-Encoding.另见http://blogs.msdn.com/b/ieinternals/archive/2012/05/16/do-not-pollute-your-pages-with-mssmarttagspreventparsing-galleryimg-imagetoolbar-pre-check-post-check.关于Cache-Control的aspx. (24认同)
  • @tim - 因为网站维护者是蠢货.对不起,没有其他方法可以描述这一点. (7认同)
  • 我觉得 [this answer](http://stackoverflow.com/a/20509354/2813263) 可能会帮助那些不确定标题的人。 (3认同)

Ray*_*jax 38

以下是使用PHP发送文件所需的内容:

$filename = "whatever.jpg";

if(file_exists($filename)){

    //Get file type and set it as Content Type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    header('Content-Type: ' . finfo_file($finfo, $filename));
    finfo_close($finfo);

    //Use Content-Disposition: attachment to specify the filename
    header('Content-Disposition: attachment; filename='.basename($filename));

    //No cache
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    //Define file size
    header('Content-Length: ' . filesize($filename));

    ob_clean();
    flush();
    readfile($filename);
    exit;
}
Run Code Online (Sandbox Code Playgroud)

正如Julian Reschke评论的那样,经过验证的答案可能会起作用,但它充满了无用的标题.内容类型应设置为文件的实际类型,或者某些浏览器(尤其是移动浏览器)可能无法正确下载.

  • 你能不能在`ob_clean`和`flush`位添加注释?他们解决了哪些潜在的问题? (3认同)
  • 如果文件名中有空格,Content-Disposition需要在文件名周围加上“ (3认同)

chi*_*org 5

如果您使用的是 Apache 或 Lighty,那么从性能的角度来看,执行此操作的“最佳”方法是使用X-Sendfile标头。请参阅本教程:https : //www.h3xed.com/programming/how-to-use-x-sendfile-with-php-apache