教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php 强制文件下载的实现代码一例

php 强制文件下载的实现代码一例

发布时间:2015-10-13   编辑:jiaochengji.com
php 强制文件下载的代码,老外写的,转摘到脚本学堂,供大家学习参考。

例子如下:

<?php
$file = 'monkey.gif';

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');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

例2,

<?php
$file = '/var/www/html/file-to-download.xyz';
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename=' . basename($file));
readfile($file);
?>

例3,readfile with accurate limit rate, using pv linux command

<?php
$file = $_SERVER['QUERY_STRING'];
header("Content-length: ".filesize($file));
header("Content-type: ".mime_content_type($file));
readfileLimit($file);

function readfileLimit($file, $limit='10M')
{
    $f = popen("pv -L $limit '$file'",'r') or return false;
    while(!feof($f))
    {
        echo fread($f, 1024);
        flush();
    }
    fclose($f);
}
?>

例4,解决ie下中文文件名乱码问题)

<?php
  $filename = $_GET['filename'];
   $file = './download/'.$filename;
    $rename = ($_GET['rename']=="") ? $filename : $_GET['rename'];           

    header('Content-Type: application/force-download');
    header("Content-Type: application/octet-stream");        
    header('Content-Length: ' . filesize($file)); 
      
    $ua = $_SERVER["HTTP_USER_AGENT"];  //判断浏览器类型  
    if (preg_match("/MSIE/", $ua)) {
        $rename = iconv("gb2312","UTF-8",$rename);    
        $encoded_filename = urlencode($rename);    
        $encoded_filename = str_replace("+", " ", $encoded_filename);        
        
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');    
    } else if (preg_match("/Firefox/", $ua)) {    
        header('Content-Disposition: attachment; filename*="utf8\'\'' . $rename . '"');    
    } else {    
        header('Content-Disposition: attachment; filename="' . $rename . '"');    
    }     
    
    readfile($file);
    exit;
?>

您可能感兴趣的文章:
PHP 强制下载文件示例代码
php强制下载mp3文件的实现代码
php实现文件强制下载代码
php 强制下载文件实例代码
php文件下载(防止中文文件名乱码)的示例代码
PHP强制下载PDF文件的代码
PHP强制下载文件方法浅析
php 强制文件下载的一段代码
php文件下载代码(多浏览器兼容、支持中文文件名)
php实现文件下载实例代码

关键词: PHP强制下载   
[关闭]
~ ~