PHP输出文件在磁盘上到浏览器

Mic*_*hel 19 php

我想在PHP中将现有文件提供给浏览器.我已经看过关于image/jpeg的例子,但是这个函数似乎将文件保存到磁盘,你必须先创建一个合适大小的图像对象(或者我只是不明白:))

在asp.net中,我通过读取字节数组中的文件然后调用context.Response.BinaryWrite(bytearray)来做到这一点,所以我在PHP中寻找类似的东西.

米歇尔

Pek*_*ica 33

fpassthru()应该做的正是你所需要的.请参阅手册条目以阅读以下示例:

<?php

// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;

?>
Run Code Online (Sandbox Code Playgroud)

请参阅此处了解所有PHP的文件系统功能.

如果它是您要提供下载的二进制文件,您可能还希望发送正确的标题,以便弹出"另存为..."对话框.请参阅此问题的第一个答案,以获取有关要发送的标头的良好示例.


Kna*_*ase 11

我用这个

  if (file_exists($file)) {


        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));

        ob_clean();
        flush();
        readfile($file);
        exit;

    } 
Run Code Online (Sandbox Code Playgroud)