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