Home  >  Article  >  php教程  >  实现“下载文件”功能

实现“下载文件”功能

WBOY
WBOYOriginal
2016-06-07 11:45:081096browse

验证用户权限后调用此函数可以下载文件,文件可以放在任意位置。
客户端不会出现乱码
不会知道所下载文件真实路径。


/**<br>  * 下载文件<br>  * @param string $file<br>  *               被下载文件的路径<br>  * @param string $name<br>  *               用户看到的文件名<br>  */<br> function download($file,$name=''){<br>     $fileName = $name ? $name : pathinfo($file,PATHINFO_FILENAME);<br>     $filePath = realpath($file);<br>     <br>     $fp = fopen($filePath,'rb');<br>     <br>     if(!$filePath || !$fp){<br>         header('HTTP/1.1 404 Not Found');<br>         echo "Error: 404 Not Found.(server file path error)<!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->";<br>         exit;<br>     }<br>     <br>     $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);<br>     $encoded_filename = urlencode($fileName);<br>     $encoded_filename = str_replace("+", "%20", $encoded_filename);<br>     <br>     header('HTTP/1.1 200 OK');<br>     header( "Pragma: public" );<br>     header( "Expires: 0" );<br>     header("Content-type: application/octet-stream");<br>     header("Content-Length: ".filesize($filePath));<br>     header("Accept-Ranges: bytes");<br>     header("Accept-Length: ".filesize($filePath));<br>     <br>     $ua = $_SERVER["HTTP_USER_AGENT"];<br>     if (preg_match("/MSIE/", $ua)) {<br>         header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');<br>     } else if (preg_match("/Firefox/", $ua)) {<br>         header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');<br>     } else {<br>         header('Content-Disposition: attachment; filename="' . $fileName . '"');<br>     }<br>     <br>     // ob_end_clean();      // 输出文件内容<br>     fpassthru($fp);<br>     exit;<br> }

AD:真正免费,域名+虚机+企业邮箱=0元

Statement:
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
Previous article:ThinkPHP环境探针Next article:ajax中国地域三级联动