Home >Backend Development >PHP Tutorial >How to implement simple file download in php, _PHP tutorial
The example in this article describes how to implement simple file downloading in PHP. Share it with everyone for your reference. The details are as follows:
The PHP file download code introduced here simply implements the download function of a picture and is not perfect yet. It is best to encapsulate it into a class or use function calls. Interested friends can improve it on this basis!
The php file download code is as follows:
<?php $file_name = "2.jpg";//需要下载的图片 define("SPATH","/php/image/");//存放图片的相对路径 $file_sub_path = $_SERVER['DOCUMENT_ROOT'];//网站根目录的绝对地址 $file_path = $file_sub_path.SPATH.$file_name;//图片绝对地址,即前面三个连接 //判断文件是否存在 if(!file_exists($file_path)){ echo "该文件不存在"; return; } $fp = fopen($file_path,"r");//打开文件 $file_size = filesize($file_path);//获取文件大小 /* *下载文件需要用到的header */ 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;//这里如果不echo,只会下载到0字节的文件 } fclose($fp); ?>
I hope this article will be helpful to everyone’s PHP programming design.