折雨的天空

新浪微薄腾讯微薄

最新碎语:最近霉到了住。哎。。。

您的位置:折雨的天空 >php开发> PHP发送文件到浏览器的一个函数

PHP发送文件到浏览器的一个函数

别人讨论的

原文地址: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);
    }
}

------------正 文 已 结 束, 感 谢 您 的 阅 读 (折雨的天空)--------------------

转载请注明本文标题和链接:《PHP发送文件到浏览器的一个函数

奖励一下

取消

分享不易,烦请有多多打赏,如您也困难,点击右边关闭即可!

扫码支持
扫码打赏,5元,10元,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

-秒后自动关闭,如已打赏,或者不愿打赏,请点击右上角关闭图标。

发表评论

路人甲 表情
看不清楚?点图切换