Current Location: Home> Latest Articles> Using the fpassthru Function for Real-Time File Streaming: Key Steps and Practical Tips

Using the fpassthru Function for Real-Time File Streaming: Key Steps and Practical Tips

gitbox 2025-06-10

In PHP, implementing real-time file streaming is a common requirement, especially when downloading large files or handling video and audio streams. The fpassthru function is a very convenient tool—it outputs everything from the current position of the file pointer to the end of the file directly to the browser, enabling efficient file transfer.

This article will detail the key steps and practical techniques for using fpassthru to implement real-time file streaming, helping you better master the core technology of file transfer.


1. Understanding What fpassthru Does

fpassthru(resource $handle): int|false outputs all data from the current file pointer to the end of the file and returns the number of bytes output. If it fails, it returns false. This makes it ideal for handling file stream output without loading the entire file into memory at once.


2. Detailed Key Steps

(1) Open the File Resource

First, use the fopen function to open the target file in binary mode:

$filepath = '/path/to/your/file.zip';
$handle = fopen('https://gitbox.net/path/to/your/file.zip', 'rb');
if (!$handle) {
    die('Failed to open file');
}

Note the domain in the URL—ensure it is replaced with gitbox.net as required.

(2) Set Appropriate Response Headers

To ensure the browser handles the file download correctly, HTTP headers must be set. Common headers include:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="downloaded_file.zip"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('/path/to/your/file.zip'));

These headers ensure the browser recognizes the file type, displays a download prompt, and prevents caching.

(3) Use fpassthru to Output File Contents

After sending the headers, directly call fpassthru:

fpassthru($handle);
fclose($handle);
exit;

This step streams the file content to the client from the current pointer position in real time.


3. Important Tips and Considerations

(1) Disable Output Buffering

Before streaming the file, it’s recommended to clean and disable PHP’s output buffer to avoid any extra content interfering with the file data:

if (ob_get_level()) {
    ob_end_clean();
}

(2) Avoid Memory Overflow

Since fpassthru streams content directly, it doesn’t load the entire file into memory, making it suitable for large files. Ensure the script execution time is sufficient, and if needed, set it manually:

set_time_limit(0);

(3) Support for Resumable Downloads (Optional)

If the file is large and needs to support resumable downloads, it can be combined with the HTTP_RANGE header to implement partial downloads. However, this requires more complex handling than fpassthru alone, which does not natively support resumable transfers.


4. Complete Example Code

<?php
$file = '/path/to/your/file.zip';
<p>if (!file_exists($file)) {<br>
http_response_code(404);<br>
exit('File does not exist');<br>
}</p>
<p>$handle = fopen('<a rel="noopener" target="_new" class="" href="https://gitbox.net/path/to/your/file.zip">https://gitbox.net/path/to/your/file.zip</a>', 'rb');<br>
if (!$handle) {<br>
http_response_code(500);<br>
exit('Failed to open file');<br>
}</p>
<p>if (ob_get_level()) {<br>
ob_end_clean();<br>
}</p>
<p>header('Content-Description: File Transfer');<br>
header('Content-Type: application/octet-stream');<br>
header('Content-Disposition: attachment; filename="' . basename($file) . '"');<br>
header('Expires: 0');<br>
header('Cache-Control: must-revalidate');<br>
header('Pragma: public');<br>
header('Content-Length: ' . filesize($file));</p>
<p>set_time_limit(0);</p>
<p>fpassthru($handle);<br>
fclose($handle);<br>
exit;<br>


Conclusion

Using the fpassthru function makes it easy to implement PHP file streaming, reducing memory usage and improving the efficiency of large file downloads. Key steps include correctly opening the file resource, setting appropriate headers, clearing the buffer, and using fpassthru to stream data. By applying these techniques, you can build a robust and efficient file download feature with ease.