Streaming Large Files in PHP
PHP's built-in file_get_contents function is a convenient way to read a file into a string, but it has a significant limitation: it loads the entire file into memory at once. This can be problematic for large files, as it can exhaust your PHP memory limit and cause your script to fail.
Fortunately, there are ways to stream a large file to a user without loading it all into memory. One technique involves using the readfile_chunked function. This function takes a filename as its argument and sends the file contents to the output buffer in chunks of a specified size.
Here's an example of how to use the readfile_chunked function:
define('CHUNK_SIZE', 1024 * 1024); // Size (in bytes) of tiles chunk // Function to read a file and display its content chunk by chunk function readfile_chunked($filename, $retbytes = TRUE) { $buffer = ''; $cnt = 0; $handle = fopen($filename, 'rb'); if ($handle === false) { return false; } while (!feof($handle)) { $buffer = fread($handle, CHUNK_SIZE); echo $buffer; ob_flush(); flush(); if ($retbytes) { $cnt += strlen($buffer); } } $status = fclose($handle); if ($retbytes && $status) { return $cnt; // return num. bytes delivered like readfile() does. } return $status; } // Check if the user is logged in // ... if ($logged_in) { $filename = 'path/to/your/file'; $mimetype = 'mime/type'; header('Content-Type: ' . $mimetype); readfile_chunked($filename); } else { echo 'Tabatha says you haven\'t paid.'; }
In this example, we define a CHUNK_SIZE constant to specify the size of each chunk (in bytes). The readfile_chunked function then reads the file in chunks and sends them to the output buffer. The ob_flush and flush functions are called to ensure that the chunks are sent to the client as they are generated.
This technique allows you to stream large files to a user without having to load the entire file into memory. It is an efficient way to deliver large files over HTTP connections.
The above is the detailed content of How Can I Stream Large Files in PHP Without Loading Them Entirely into Memory?. For more information, please follow other related articles on the PHP Chinese website!