PHP uses header method to achieve file download function

Source: Internet
Author: User
Tags fread ranges readfile response code
This article mainly introduces PHP use header way to achieve file download function, very good, with reference value, the need for friends can refer to the next

Let me introduce you to the PHP header () function

Definition and usage

The header () function sends the original HTTP header to the client.

It is important to recognize that the header () function must be called before any actual output is sent (in PHP 4 and later, you can use output caching to resolve this issue):


Grammar

Header (String,replace,http_response_code)
number description
string required. Specifies the string of headers to send.
replace

optional. Indicates whether the header replaces the previous header, or adds a second header.

default is True (replace). False (multiple headers of the same type are allowed).

Http_response_code Optional. Forces the HTTP response code to the specified value. (Available in PHP 4 and later)

PHP file download can use the HTTP request header plus PHP IO can be implemented, a long time ago wrote such a function, and then the code is gone, today record

1, first look at a normal HTTP request

http/1.1 okserver:tenginecontent-type:application/octet-streamcontent-length:5050697connection: Keep-alivedate:thu, Oct 11:24:46 gmtaccept-ranges:bytescontent-disposition:attachment; Filename=down/20170928/zjbb_2.9.5.apkexpires:thu, Oct 11:25:46 Gmtcache-control:max-age=60via: CACHE25.L2EU6-1[0,200-0,H], cache16.l2eu6-1[16,0], cache8.cn891[0,200-0,h], Cache8.cn891[1,0]age:1733678x-cache: Hit Tcp_mem_hit dirn:6:277104755 Mlen:-1x-swift-savetime:sat, Oct 00:50:47 gmtx-swift-cachetime: 93312000timing-allow-origin: *eagleid:b73d0e1c15095411645886178e

2. Some common header functions

Header (' http/1.1 OK '); OK normal access header (' http/1.1 404 Not Found '); Notification Browser page does not exist header (' http/1.1 301 Moved permanently '); Set the address to be permanently redirected 301header (' location:http://www.test.con/'); Jump to a new address header (' refresh:10; url=http://www.test.con/'); The delayed turn is the jump header (' x-powered-by:php/7.0.0 ') every few seconds; Modify the X-powered-by Information header (' Content-language:en '); Document Language header (' content-length:1234 '); Set the content Length header (' last-modified: '. Gmdate (' d, D M Y h:i:s ', $time). ' GMT '); Tells the browser the last time the header was modified (' http/1.1 304 not Modified '); Tells the browser that the document content has not changed # # #内容类型 # # #header (' content-type:text/html; Charset=utf-8 '); Page encoding header (' Content-type:text/plain '); Plain Text Format header (' Content-type:image/jpeg '); JPG, Jpegheader (' content-type:application/zip '); Zip file header (' Content-type:application/pdf '); PDF file Header (' Content-type:audio/mpeg '); Audio file header (' Content-type:text/css '); CSS file header (' Content-type:text/javascript '); JS file header (' Content-type:application/json '); Jsonheader (' content-type:application/pdf ');Pdfheader (' Content-type:text/xml '); Xmlheader (' Content-type:application/x-shockw**e-flash '); Flash animation ######## #声明一个下载的文件 # # #header (' Content-type:application/octet-stream '); header (' Content-disposition: Attachment Filename= "Itblog.zip"); header (' content-transfer-encoding:binary '); ReadFile (' test.zip '); ######## #对当前文档禁用缓存 # # # Header (' Cache-control:no-cache, No-store, max-age=0, Must-revalidate '); header (' Expires:mon, Jul 1997 05:00:00 GMT ') ; ######## #显示一个需要验证的登陆对话框 # # #header (' http/1.1 401 Unauthorized '); header (' Www-authenticate:basic realm= ' Top Secret ') ; ######## #声明一个需要下载的xls文件 # # #header (' content-disposition:attachment; filename=abc.xlsx '); header (' Content-type: Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet '); header (' Content-length: '. FileSize ('./ Test.xls '); header (' content-transfer-encoding:binary '); header (' cache-control:must-revalidate '); header (' Pragma: Public '); ReadFile ('./test.xls ');

3, look at the download to use the request header

Header ("Content-type:application/octet-stream"), Header ("Accept-ranges:bytes"), Header ("Accept-length:". $file _ Size); header ("Content-disposition:attachment; Filename= ". $filename);
    • Content-type: File type

    • Accept-ranges: Indicates the type or range of the received data, and the picture is binary so it needs to be transmitted in bytes

    • Accept-length: Indicates the size of the received file, php file download need to tell the browser how big the file downloaded

    • Content-disposition: Attachment only need to give the file name to the past, this name is the name of the file displayed when downloading

4, PHP file operation appears earlier, the file name is in Chinese need to pay attention to transcoding

$filename =iconv ("UTF-8", "GB2312", $filename);

5, php file download mechanism is the first nginx to read the file information into the server memory, and then use the request header to the file binary information through the browser to the client

Feof is used to determine if the file has been read to the end, Fread used to read the file into the buffer, the buffer size is 1024, while reading the data to the browser. In order to download security, each read data is counted in bytes. Closes the input stream after the file has been read

Attention:

A, if there is a problem in the process of running, you can empty (erase) The output buffer, use the following code to

ob_clean();

B, a lot of people like to use ReadFile, if it is a large file, there may be problems

Full code

<?php Ob_clean (); $action = $_get[' action ']; $filename = Base64_decode ($action);//Parameters encode $filepath = '/data/www/www.test.com/'. $filename; if (!file_exists ($filepath)) {  exit;} $fp =fopen ($filepath, "R"), $filesize =filesize ($filepath), Header (" Content-type:application/octet-stream "); Header ("Accept-ranges:bytes"); Header ("Accept-length:". $filesize); Header ("content-disposition:attachment; Filename= ". $filename); $buffer = 1024; $buffer _count=0; while (!feof ($fp) && $file _size-$buffer _count>0) {$data =fread ($fp, $buffer); $buffer _count+= $buffer;  Echo $data; } fclose ($FP);? >

PS: below to see a sample code PHP how to use header file headers to achieve file download

The specific code looks like this:

 $file = $_get[' file '];if (file_exists ($file)) {header ("Content-type: Application/octet-stream "); $filename = basename ($file); header (" Content-disposition:attachment;filename = ". $ FileName), header ("Accept-ranges:bytes"), Header ("Accept-length:". FileSize ($file)); ReadFile ($file);} else{echo "<script>alert (' File not present ') </script>";} 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.