Detailed explanation based on php download file

  • 2020-06-03 06:07:55
  • OfStack

php downloads files, such as txt files.
The effect is to pop up the browser's own download box and save as an operation. Memory leaks and timeouts can sometimes occur.
To timeout, set set_time_limit(0);
If there is a memory leak, it may be due to the amount of data taken out of the database.
If you read from a file, and you run out of memory, then the code is read incorrectly and you call files or filegetcontens
If it's fopen, give it a buffer, a fixed size, read it in and write it in, no memory runs out.
Such as code:

if (file_exists($file_path)) { // If the file exists 
$handle = fopen($file_path, "r");
while (!feof($handle)) {
$content = fgets($handle, 4096); // read 1 line 
echo $content; // Output to buffer, i.e php://stdout . The buffer setting value is reached by tcp To the browser for output   1 As to the 512 The bytes are then exported over the network to the browser 

But before output, it is called once, @ob_end_flush (); No loop call, just one call.
@ ob_end_flush (); // Flush out the output buffer contents and close the buffer

File Download:
content-type :// Download format, the browser can not resolve the format will pop up the download box

header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Transfer-Encoding: binary");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
Header("Content-type: application/octet-stream");  // Response content type 
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($filename). ' bytes');
Header('Content-Disposition: attachment; filename='.$filename);  //HTTP Response headers 

Related articles: