Home > php教程 > php手册 > php实现简单文件下载的方法,

php实现简单文件下载的方法,

WBOY
Release: 2016-06-13 09:16:06
Original
847 people have browsed it

php实现简单文件下载的方法,

本文实例讲述了php实现简单文件下载的方法。分享给大家供大家参考。具体如下:

这里介绍的php文件下载代码,只是简单实现了一张图片的下载功能,还不完善,最好是封装到一个类里,或是采用函数调用。感兴趣的朋友可以在此基础上加以完善!

php文件下载代码如下:

<&#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

希望本文所述对大家的php程序设计有所帮助。

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template