分享一个超好用的php header下载函数

2015-01-24信息快讯网

这篇文章主要为大家分享一个超好用的php header下载函数,需要的朋友可以参考下

<?php
/**
 * 发送文件
 *
 * @author: legend([email protected])
 * @link: http://www.ugia.cn/?p=109
 * @description: send file to client
 * @version: 1.0
 *
 * @param string   $fileName      文件名称或路径
 * @param string   $fancyName     自定义的文件名,为空则使用filename
 * @param boolean  $forceDownload 是否强制下载
 * @param integer  $speedLimit    速度限制,单位为字节,0为不限制,不支持windows服务器
 * @param string   $$contentType  文件类型,默认为application/octet-stream
 *
 * @return boolean
 */
function sendFile($fileName, $fancyName = '', $forceDownload = true, $speedLimit = 0, $contentType = '')
{
    if (!is_readable($fileName))
    {
        header("HTTP/1.1 404 Not Found");
        return false;
    }

$fileStat = stat($fileName); $lastModified = $fileStat['mtime']; $md5 = md5($fileStat['mtime'] .'='. $fileStat['ino'] .'='. $fileStat['size']); $etag = '"' . $md5 . '-' . crc32($md5) . '"';

header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT'); header("ETag: $etag"); if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified) { header("HTTP/1.1 304 Not Modified"); return true; }

if (isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_UNMODIFIED_SINCE']) < $lastModified) { header("HTTP/1.1 304 Not Modified"); return true; }

if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) { header("HTTP/1.1 304 Not Modified"); return true; }

if ($fancyName == '') { $fancyName = basename($fileName); } if ($contentType == '') { $contentType = 'application/octet-stream'; }

$fileSize = $fileStat['size']; $contentLength = $fileSize; $isPartial = false;

if (isset($_SERVER['HTTP_RANGE'])) { if (preg_match('/^bytes=(d*)-(d*)$/', $_SERVER['HTTP_RANGE'], $matches)) { $startPos = $matches[1]; $endPos = $matches[2];

if ($startPos == '' && $endPos == '') { return false; } if ($startPos == '') { $startPos = $fileSize - $endPos; $endPos = $fileSize - 1; } else if ($endPos == '') { $endPos = $fileSize - 1; }

$startPos = $startPos < 0 ? 0 : $startPos; $endPos = $endPos > $fileSize - 1 ? $fileSize - 1 : $endPos;

$length = $endPos - $startPos + 1;

if ($length < 0) { return false; }

$contentLength = $length; $isPartial = true; } } // send headers if ($isPartial) { header('HTTP/1.1 206 Partial Content'); header("Content-Range: bytes $startPos-$endPos/$fileSize"); } else { header("HTTP/1.1 200 OK"); $startPos = 0; $endPos = $contentLength - 1; }

header('Pragma: cache'); header('Cache-Control: public, must-revalidate, max-age=0'); header('Accept-Ranges: bytes'); header('Content-type: ' . $contentType); header('Content-Length: ' . $contentLength); if ($forceDownload) { header('Content-Disposition: attachment; filename="' . rawurlencode($fancyName). '"');//汉字自动转为URL编码 header('Content-Disposition: attachment; filename="' . $fancyName. '"'); }

header("Content-Transfer-Encoding: binary"); $bufferSize = 2048;

if ($speedLimit != 0) { $packetTime = floor($bufferSize * 1000000 / $speedLimit); }

$bytesSent = 0; $fp = fopen($fileName, "rb"); fseek($fp, $startPos);

//fpassthru($fp); while ($bytesSent < $contentLength && !feof($fp) && connection_status() == 0 ) { if ($speedLimit != 0) { list($usec, $sec) = explode(" ", microtime()); $outputTimeStart = ((float)$usec + (float)$sec); }

$readBufferSize = $contentLength - $bytesSent < $bufferSize ? $contentLength - $bytesSent : $bufferSize; $buffer = fread($fp, $readBufferSize);

echo $buffer;

ob_flush(); flush();

$bytesSent += $readBufferSize; if ($speedLimit != 0) { list($usec, $sec) = explode(" ", microtime()); $outputTimeEnd = ((float)$usec + (float)$sec); $useTime = ((float) $outputTimeEnd - (float) $outputTimeStart) * 1000000; $sleepTime = round($packetTime - $useTime); if ($sleepTime > 0) { usleep($sleepTime); } } }

return true; } ?>

PHP的error_reporting错误级别变量对照表
phpmailer在服务器上不能正常发送邮件的解决办法
采用memcache在web集群中实现session的同步会话
CodeIgniter实现更改view文件夹路径的方法
PHP关于htmlspecialchars、strip_tags、addslashes的解释
PHP+Memcache实现wordpress访问总数统计(非插件)
php+memcache实现的网站在线人数统计代码
CodeIgniter安全相关设置汇总
php foreach正序倒序输出示例代码
PHPMailer发送HTML内容、带附件的邮件实例
ThinkPHP之foreach标签使用概述
使用ThinkPHP+Uploadify实现图片上传功能
修改ThinkPHP缓存为Memcache的方法
ThinkPHP2.0读取MSSQL提示Incorrect syntax near the keyword 'AS'的解决方法
Thinkphp中Create方法深入探究
PHP中多维数组的foreach遍历示例
Codeigniter上传图片出现“You did not select a file to upload”错误解决办法
让codeigniter与swfupload整合的最佳解决方案
PHP数据库万能引擎类adodb配置使用以及实例集锦
采用header定义为文件然后readfile下载(隐藏下载地址)
preg_match_all使用心得分享
php缓冲 output_buffering和ob_start使用介绍
PHP $_FILES中error返回值详解
header导出Excel应用示例
解决php接收shell返回的结果中文乱码问题
php多种形式发送邮件(mail qmail邮件系统 phpmailer类)
使用php伪造referer的方法 利用referer防止图片盗链
修改apache配置文件去除thinkphp url中的index.php
PHP获取php,mysql,apche的版本信息示例代码
windows下PHP_intl.dll正确配置方法(apache2.2+php5.3.5)
eaglephp使用微信api接口开发微信框架
php安装xdebug/php安装pear/phpunit详解步骤(图)
php用header函数实现301跳转代码实例
php堆排序(heapsort)练习
php中autoload的用法总结
PHP中spl_autoload_register函数的用法总结
Php header()函数语法及使用代码
©2014-2024 dbsqp.com