折雨的天空
PHP发送文件到浏览器的一个函数
2012-5-14 我好笨

别人讨论的



原文地址:http://pastie.org/3848723



源码如下:


<?php

/**
* 从 Ruby On Rails 迁移到 PHP 的 send_file() 方法
* 参见:http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file
*/
function send_file($path, $options = array()) {
if (! is_file($path) || ! is_readable($path)) {
throw new Exception("没有找到指定的文件");
}

if (! isset($options['x_sendfile'])) {
$options['x_sendfile'] = TRUE;
}

if (! isset($options['filename']) && ! isset($options['url_base_filename'])) {
$options['filename'] = basename($path);
}

$defaults = array(
'type' => 'application/octet-stream',
'disposition' => 'attachment'
);
$options = array_merge($defaults, $options);

foreach (array('type', 'disposition') as $arg) {
if (is_null($options[$arg])) {
throw new InvalidArgumentException("{$arg} option required");
}
}

$disposition = $options['disposition'];
if (isset($options['filename'])) {
if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
$encoded_filename = str_replace("+", "%20", urlencode($options['filename']));
$disposition .= "; filename=\"{$encoded_filename }\"";
} else {
$disposition .= "; filename=\"{$options['filename']}\"";
}
}

if (! headers_sent()) {
header("Content-Type: {$options['type']}");
header("Content-Disposition: {$disposition}");
header("Content-Transfer-Encoding: binary");
}

$x_sendfile_supported = $options['x_sendfile'] && in_array('mod_xsendfile', apache_get_modules());
if (! headers_sent() && $x_sendfile_supported) {
header("X-Sendfile: {$path}");
} else {
@readfile($path);
}
}

发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容