PHP uses the header method to download files,

Source: Internet
Author: User

PHP uses the header method to download files,

First, we will introduce the PHP header () function.

Definition and usage

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

It is important to realize that the header () function must be called before any actual output is sent (in PHP 4 and later versions, you can use the output cache to solve this problem):

<Html> <? Php // result error // output header ('location: http://www.example.com/') exists before calling header ();?>

Syntax

header(string,replace,http_response_code)


Quantity Description
String Required. Specifies the header string to be sent.
Replace

Optional. Indicates whether the header replaces the previous header or adds the second header.

The default value 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. (PHP 4 and later versions are available)


Php File Download can be implemented using the http request header and php I/O. I wrote this function a long time ago, but the code is gone. Record it today.

1. First look at a normal http Request

HTTP/1.1 200 OKServer: TengineContent-Type: application/octet-streamContent-Length: 5050697Connection: keep-aliveDate: Thu, 12 Oct 2017 11:24:46 GMTAccept-Ranges: bytesContent-Disposition: attachment; filename=down/20170928/zjbb_2.9.5.apkExpires: Thu, 12 Oct 2017 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:  TCP_MEM dirn:6:277104755 mlen:-1X-Swift-SaveTime: Sat, 14 Oct 2017 00:50:47 GMTX-Swift-CacheTime: 93312000Timing-Allow-Origin: *EagleId: b73d0e1c15095411645886178e

2. Some common header Functions

Header ('HTTP/1.1 200 OK '); // OK normal access header ('HTTP/1.1 404 Not Found '); // notify the browser that the page does not contain the header ('HTTP/1.1 301 Moved Permanently '); // set the address to be Permanently redirected to the 301 header ('location: http://www.test.con /'); // jump to a new address header ('refresh: 10; url = http://www.test.con/'); // The delayed redirection is the jump header ('x-Powered-: PHP/7.0.0 '); // modify the X-Powered-By header ('content-language: en'); // the header of the Document language ('content-Length: 1234 '); // set the Content Length header ('Last-Modified :'. gmdate ('d, d m y h: I: s', $ time ). 'gmt'); // tell the browser the last modification time header ('HTTP/1.1 304 Not modified '); // tell the browser that the document Content has not changed ### Content Type ### header ('content-Type: text/html; charset = UTF-8 '); // webpage encoding header ('content-Type: text/plain '); // plain text format header ('content-Type: image/jpeg '); // JPG and Response header ('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 '); // Response Header ('content-type: text/xml'); // xmlheader ('content-Type: application/x-shockw ** e-flash '); // Flash Animation ######### declare a downloaded file ### header ('content-Type: application/octet-stream '); header ('content-Disposition: attachment; filename = "ITblog.zip" '); header ('content-Transfer-Encoding: binary'includedreadfile('test.zip '); ######## disable caching for the current document ### header ('cache-Control: no-Cache, no-store, max-age = 0, must-revalidate '); header ('expires: Mon, 26 Jul 1997 05:00:00 gmt '); ######## display a Login Dialog box to be verified ### header ('HTTP/1.1 401 unauthorized'); header ('www-Authenticate: basic realm = "Top Secret" '); ######## declare an xls file to be downloaded ### 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. Check the request header used for download.

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. The image is binary and must be transmitted in bytes.
  • Accept-Length: indicates the size of the received file. to download a PHP file, you must inform the browser of the size of the file to be downloaded.
  • Content-Disposition: you only need to give the file name to the attachment. This name is the file name displayed during download.

4. php file operations appear early. When the file name is Chinese, you must pay attention to transcoding.

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

5. the php File Download mechanism is to first read the file information into the server memory by nginx, and then use the request header to transmit the binary information of the file to the client through a browser.

Feof is used to determine whether the file has been read to the end. fread is used to read the file into the buffer zone. The buffer size is 1024. when reading the file, the data is output to the browser. To ensure the download security, bytes are counted every time data is read. Close the input stream after the file is read.

Note:

A. if a problem occurs during running, clear (erase) the output buffer and use the following code.

ob_clean();

B. Many users prefer readfile. If it is a large file, it may be faulty.

Complete code

<? Php ob_clean (); $ action =$ _ GET ['action']; $ filename = base64_decode ($ action ); // The passed parameter encode $ filepath = '/data/www/www.test.com/'.w.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: Let's take a look at how php uses the header file to download files.

The Code is as follows:

$ 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 does not exist') </script> ";}

Summary

The above section describes how to use the header method to download files in PHP. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!


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.