Home > Backend Development > PHP Tutorial > PHP function example for downloading files (picture and text)

PHP function example for downloading files (picture and text)

WBOY
Release: 2016-07-25 08:57:04
Original
981 people have browsed it
Share a php download function, used to download specified files, regardless of file format. Friends in need can refer to it.

Examples of functions for downloading files in php are as follows:

<?php
/**
* php下载文件
* $filename=$_SERVER['DOCUMENT_ROOT']."/test/file/20130503/20130503150036_85945.doc";
* $title="下载测试9";
* down($filename,$title);
* edit by bbs.it-home.org
*/ 
//$filename 必须是路径,不是url
 function down($filename,$title=''){
     $file = fopen($filename,"r"); 
     $filesize = filesize($filename);
     $encoded_filename = urlencode($title);
     $encoded_filename = str_replace("+", "%20", $title);
     $ua = $_SERVER["HTTP_USER_AGENT"];
     if (preg_match("/MSIE/is", $ua)) {  
         $file_name = urlencode($title);
         header("Pragma: public"); header("Expires: 0");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Content-Type: application/force-download");
         header('Content-Type: application/vnd.ms-excel; charset=utf-8');
         header("Content-Transfer-Encoding: binary");
         header('Content-Disposition: attachment; filename='.$file_name);
     } else {
        header('Content-Type: application/octet-stream');
         if (preg_match("/Firefox/is", $ua)) {  
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $title . '"');
         } else {  
            header('Content-Disposition: attachment; filename="' . $title . '"');
         }
     }
    echo fread($file, $filesize);
    fclose($file);
}
?>
Copy after login

The operation effect is as follows: PHP function example for downloading files (picture and text)



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template