Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of downloading File based on php

Shulou Source: shulou.com Published: 2022-06-03 06:13:10 11月16日 Update

This article shares with you the content of a sample analysis of php-based downloads. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Php downloads files, such as txt files.

The effect is to pop up the download box that comes with the browser and save it as an operation. Sometimes memory overflows and timeouts occur.

If you time out, set set_time_limit (0)

If a memory overflow occurs, it may be due to the large amount of data fetched from the database.

If you are reading from a file, if there is a memory overflow, the code will not be read correctly until you call files or filegetcontens.

If it is fopen, give a buffer, fixed size, read and then write, there will be no memory overflow.

Such as the code:

If (file_exists ($file_path)) {/ / if the file exists

$handle = fopen ($file_path, "r")

While (! feof ($handle)) {

$content = fgets ($handle, 4096); / / read a line

Echo $content; / / outputs to the buffer, that is, php://stdout. When the buffer setting value is reached, the tcp will send it to the browser for output. Generally, 512 bytes will be output to the browser through the network.

}

Fclose ($handle)

}

But before the output, call @ ob_end_flush () once; you can't call it looping, just call it once.

@ ob_end_flush (); / / flush out (send) the contents of the output buffer and close the buffer

File download:

The format of content-type:// download, the format that the browser cannot parse will pop up the download box.

The copy code is as follows:

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 header

Thank you for reading! This is the end of this article on "sample analysis based on php download files". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Tags: File buffer output code memory content browser buffer browse example analysis that is data more format article good practical one line size Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Shulou Information MariaDB OPPO Reno Shulou Technology