How to implement simple file download in php, _PHP tutorial

WBOY
Release: 2016-07-13 10:08:27
Original
760 people have browsed it

How to implement simple file download in php,

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:

<&#63;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);
&#63;>
Copy after login

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/950894.htmlTechArticleHow to implement simple file downloads in PHP. This article describes how to implement simple file downloads in PHP. Share it with everyone for your reference. The details are as follows: The php file download code introduced here...
Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!