磁盘上的PHP输出文件到浏览器 [英] PHP output file on disk to browser

查看:284
本文介绍了磁盘上的PHP输出文件到浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用PHP将现有文件提供给浏览器. 我已经看过有关image/jpeg的示例,但是该功能似乎将文件保存到磁盘上,您必须先创建一个大小合适的图像对象(否则我只是不理解:))

I want to serve an existing file to the browser in PHP. I've seen examples about image/jpeg but that function seems to save a file to disk and you have to create a right sized image object first (or I just don't understand it :))

在asp.net中,我通过读取字节数组中的文件然后调用context.Response.BinaryWrite(bytearray)来完成此操作,因此我正在PHP中寻找类似的东西.

In asp.net I do it by reading the file in a byte array and then call context.Response.BinaryWrite(bytearray), so I'm looking for something similar in PHP.

米歇尔

推荐答案

fpassthru() 应该可以完全满足您的需求.请参见手册,以阅读以下示例:

There is fpassthru() that should do exactly what you need. See the manual entry to read about the following example:

<?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;

?>

有关所有内容,请参见 此处 PHP的文件系统功能.

See here for all of PHP's filesystem functions.

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

If it's a binary file you want to offer for download, you probably also want to send the right headers so the "Save as.." dialog pops up. See the 1st answer to this question for a good example on what headers to send.

这篇关于磁盘上的PHP输出文件到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆