php如何实现文件下载功能(附代码)
php实现文件下载我们需要用到header函数来发送相关信息给客户端浏览器,同时再结合filesize函数来读取文件大小并进行下载操作,下面我们一起来看看相关例子。
简单的文件下载只需要使用HTML的连接标记,并将属性href的URL值指定为下载的文件即可。所示:
如果通过上面的代码实现文件下载,只能处理一些浏览器不能默认识别的MIME类型文件,例如当访问book.rar文件时,浏览器并没有直接打开,而是弹出一个下载提示框,提示用户“下载”还是“打开”等处理方式。但如果需要下载后缀名为.html的网页文件、图片文件及PHP程序脚本文件等,使用这种连接形式,则会将文件内容直接输出到浏览器中,并不会提示用户下载。
header(‘Content-Type:imge/gif'); //发送指定文件MIME类型的头信息 header(‘Content-Disposition:attachment; filename=”test.gif”‘); //发送描述文件的头信息,附件和文件名 header(‘Content-Length:3390′); //发送指定文件大小的信息,单位字节
如果使用header()函数向浏览器发送了这三行头信息,图片test.gif就不会直接在浏览器中显示,而让浏览器将该文件形成下载的形式。在函数header()中,“Content-Type”指定了文件的MIME类型,“Content_Disposition”用于文件的描述,值“attachment; filename=”test.gif””说明这是一个附件,并且指定了下载后的文件名,“Content_Length”则给出了被下载文件的大小。
设置完头部信息以后,需要将文件的内容输出到浏览器,以便进行下载。可以使用PHP中的文件系统函数将文件内容读取出来后,直接输出给浏览器。最方便的是使用readfile()函数,将文件内容读取出来直接输出。下载文件test.gif的所示:
<?php $filename = "test.gif"; header('Content-Type:image/gif'); //指定下载文件类型 header('Content-Disposition: attachment; filename="'.$filename.'"'); //指定下载文件的描述 header('Content-Length:'.filesize($filename)); //指定下载文件的大小 //将文件内容读取出来并直接输出,以便下载 readfile($filename); ?>
上面如果碰到中文名字就会无法正常下载了,对于中文名字下载文件我又找到一个文件下载实例代码
<?php header("Content-type:text/html;charset=utf-8"); // $file_name="cookie.jpg"; $file_name="圣诞狂欢.jpg"; //用以解决中文不能显示出来的问题 $file_name=iconv("utf-8","gb2312",$file_name); $file_sub_path=$_SERVER['DOCUMENT_ROOT']."marcofly/phpstudy/down/down/"; $file_path=$file_sub_path.$file_name; //首先要判断给定的文件存在与否 if(!file_exists($file_path)){ echo "没有该文件文件"; return ; } $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); ?>
header("Content-type:text/html;charset=utf-8")的作用:在服务器响应浏览器的请求时,告诉浏览器以编码格式为UTF-8的编码显示该内容
关于file_exists()函数不支持中文路径的问题:因为php函数比较早,不支持中文,所以如果被下载的文件名是中文的话,需要对其进行字符编码转换,否则file_exists()函数不能识别,可以使用iconv()函数进行编码转换
$file_sub_path() 我使用的是绝对路径,执行效率要比相对路径高
Header("Content-type: application/octet-stream")的作用:通过这句代码客户端浏览器就能知道服务端返回的文件形式 Header("Accept-Ranges: bytes")的作用:告诉客户端浏览器返回的文件大小是按照字节进行计算的 Header("Accept-Length:".$file_size)的作用:告诉浏览器返回的文件大小 Header("Content-Disposition: attachment; filename=".$file_name)的作用:告诉浏览器返回的文件的名称
以上四个Header()是必需的
fclose($fp)可以把缓冲区内最后剩余的数据输出到磁盘文件中,并释放文件指针和有关的缓冲区
【相关教程推荐】
1. php编程从入门到精通全套视频教程
2. php从入门到精通
3. bootstrap教程

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
