Home  >  Article  >  Backend Development  >  PHP文件下载函数(代码)

PHP文件下载函数(代码)

WBOY
WBOYOriginal
2016-06-20 13:03:371022browse

php实现文件下载的函数,具体函数代码如下:

<p>function download($file_url,$new_name=''){</p> if(!isset($file_url)||trim($file_url)==''){<br /> return '500';<br /> }<br /> if(!file_exists($file_url)){ //检查文件是否存在<br /> return '404';<br /> }<br /> $file_name=basename($file_url);<br /> $file_type=explode('.',$file_url);<br /> $file_type=$file_type[count($file_type)-1];<br /> $file_name=trim($new_name=='')?$file_name:urlencode($new_name).'.'.$file_type;<br /> $file_type=fopen($file_url,'r'); //打开文件<br /> //输入文件标签<br /> header("Content-type: application/octet-stream");<br /> header("Accept-Ranges: bytes");<br /> header("Accept-Length: ".filesize($file_url));<br /> header("Content-Disposition: attachment; filename=".$file_name);<br /> //输出文件内容<br /> echo fread($file_type,filesize($file_url));<br /> fclose($file_type);<br /><p>}</p>

注意以上检查文件是否存在是通过file_exists这个函数的,但这个函数只能检查相对于当前服务器网站目录里面的文件,如果是互联网上的远程文件,可以通过本站如下这篇文章:php判断远程文件是否存在的办法


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