Home >Backend Development >PHP Problem >How to download files from server in php
PHP can download files on the server through the custom function method downtemplateAction(). In its method body, there are functions such as determining whether the file exists, whether it has been successfully downloaded, and closing the file. .
Related recommendations: "php tutorial"
Specific examples are as follows:
/** * @todo 下载文件 */ public function downtemplateAction(){ header("Content-type:text/html;charset=utf-8"); $file_name = "template.xlsx"; $file_name = iconv("utf-8","gb2312",$file_name); $file_sub_path = APP_PATH.'/data/obj/2018-03-21/'; $file_path=$file_sub_path.$file_name; if(!file_exists($file_path)) { echo "下载文件不存在!"; exit; } $fp=fopen($file_path,"r"); $file_size=filesize($file_path); //下载文件需要用到的头 Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length:".$file_size); Header("Content-Disposition: attachment; filename=".$file_name); $buffer=1024; $file_count=0; while(!feof($fp) && $file_count<$file_size) { $file_con=fread($fp,$buffer); $file_count+=$buffer; echo $file_con; } fclose($fp); //关闭这个打开的文件 }
The above is the detailed content of How to download files from server in php. For more information, please follow other related articles on the PHP Chinese website!