PHP uses header to realize file download function

  • 2021-08-10 07:29:38
  • OfStack

First, let's 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, you can use output caching to solve this problem):


<html>
<?php
//  The result is wrong 
//  When calling  header()  Output already exists 
header('Location: http://www.example.com/');
?>

Grammar


header(string,replace,http_response_code)

描述
string 必需。规定要发送的报头字符串。
replace

可选。指示该报头是否替换之前的报头,或添加第2个报头。

默认是 true(替换)。false(允许相同类型的多个报头)。

http_response_code 可选。把 HTTP 响应代码强制为指定的值。(PHP 4 以及更高版本可用)

php file download can use http request header plus php IO can be achieved, a long time ago wrote such a function, later the code is gone, today record 1

1. Look at 1 normal http request first


HTTP/1.1 200 OK
Server: Tengine
Content-Type: application/octet-stream
Content-Length: 5050697
Connection: keep-alive
Date: Thu, 12 Oct 2017 11:24:46 GMT
Accept-Ranges: bytes
Content-Disposition: attachment; filename=down/20170928/zjbb_2.9.5.apk
Expires: Thu, 12 Oct 2017 11:25:46 GMT
Cache-Control: max-age=60
Via: cache25.l2eu6-1[0,200-0,H], cache16.l2eu6-1[16,0], cache8.cn891[0,200-0,H], cache8.cn891[1,0]
Age: 1733678
X-Cache: HIT TCP_MEM_HIT dirn:6:277104755 mlen:-1
X-Swift-SaveTime: Sat, 14 Oct 2017 00:50:47 GMT
X-Swift-CacheTime: 93312000
Timing-Allow-Origin: *
EagleId: b73d0e1c15095411645886178e

2, 1 Some common header functions


header('HTTP/1.1 200 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  301
header('Location: http://www.test.con/'); // Jump to 1 A new address 
header('Refresh: 10; url=http://www.test.con/'); // Delayed steering   That is, jump every few seconds 
header('X-Powered-By: PHP/7.0.0'); // Modify  X-Powered-By Information 
header('Content-language: en'); // Document language 
header('Content-Length: 1234'); // Set content length 
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT'); // Tell the browser that the last 1 Time of second modification 
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'); // Web page coding 
header('Content-Type: text/plain'); // Plain text format 
header('Content-Type: image/jpeg'); //JPG , JPEG
header('Content-Type: application/zip'); // ZIP Documents 
header('Content-Type: application/pdf'); // PDF Documents 
header('Content-Type: audio/mpeg'); //  Audio file 
header('Content-type: text/css'); //css Documents 
header('Content-type: text/javascript'); //js Documents 
header('Content-type: application/json'); //json
header('Content-type: application/pdf'); //pdf
header('Content-type: text/xml'); //xml
header('Content-Type: application/x-shockw**e-flash'); //Flash Animation 
######
### Declaration 1 Downloaded files ###
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="ITblog.zip"');
header('Content-Transfer-Encoding: binary');
readfile('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 1 Login dialog boxes that need to be verified ###
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
######
### Declaration 1 A need to download xls Documents ###
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 request header to 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 received data. Pictures belong to binary system, so they need to be transmitted in bytes Accept-Length: Indicates the size of the received file. For php file download, you need to tell the browser how big the downloaded file is Content-Disposition: The attachment only needs to give the file name to the past, which is the file name displayed when downloading

4. The file operation of php appeared earlier, and it is necessary to pay attention to transcoding when the file name is Chinese


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

5. The file download mechanism of php is that nginx first reads the file information into the server memory, and then transmits the file binary information to the client through the browser by using the request header

feof is used to judge whether the file has been read to the end. fread is used to read the file into a buffer. The size of the buffer is 1024. 1 reads 1 and outputs the data to the browser. For the safety of downloading, bytes are counted every time data is read. Close the input stream after reading the file

Note:

a, if there is a problem in the process of running, you can empty (erase) the output buffer by using the following code

ob_clean();

b, many people like to use readfile, if it is a large file, there may be problems

Complete code


<?php
 ob_clean();
 $action = $_GET['action'];
 $filename = base64_decode($action);// Parameters of transmission encode It's over 
 $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: Let's see how one example code php can download files through the header of header

The specific 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>";
}

Summarize


Related articles: