Php-based file download details

Source: Internet
Author: User

Php downloads files, such as txt files.
The result is that the browser's built-in download box is displayed, and the Save As operation is displayed. Sometimes memory overflow and timeout may occur.
If timeout occurs, Set Set_time_limit (0 );
Memory overflow may occur because the amount of data retrieved from the database is too large.
If it is read from a file, memory overflow occurs, that is, the code reading method is incorrect. Only files or filegetcontens can be called.
If fopen is used, a buffer is provided, with a fixed size. The buffer is read and written without memory overflow.
Such as code:
Copy codeCode: if (file_exists ($ file_path) {// if the file exists
$ Handle = fopen ($ file_path, "r ");
While (! Feof ($ handle )){
$ Content = fgets ($ handle, 4096); // read a row
Echo $ content; // output to the buffer, that is, php: // stdout. After the buffer setting value is reached, the tcp transmission will be sent to the browser for output. Generally, the output will be 512 bytes to the browser through the network.
}
Fclose ($ handle );
}

But before the output, call it once. @ ob_end_flush (); the call can only be called once.
@ Ob_end_flush (); // extracts (sends) the output buffer content and closes the buffer.

File Download:
Content-type: // download format. If the format cannot be parsed by the browser, the download box is displayed.
Copy codeThe 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

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.