Current Location: Home> Latest Articles> How to use fpassthru to implement file streaming in PHP

How to use fpassthru to implement file streaming in PHP

gitbox 2025-05-28

In PHP, the fpassthru function is a very practical file streaming tool, which is especially suitable for directly outputting file content to the client, such as pictures, videos, downloading files, etc. Its biggest advantage is that it can efficiently transfer file content to the browser without reading the entire file into memory, thereby saving resources and avoiding memory overflow issues.

This article will introduce in detail how to use the fpassthru function to implement file streaming, and combine a complete sample code to help you get started quickly.


What is fpassthru?

fpassthru is a function in PHP file operation, and the function is to output from the current file pointer position until the end of the file. It is often used in conjunction with fopen . After opening the file, the file contents are directly output to the browser.

Function prototype:

 int fpassthru ( resource $handle )
  • $handle is a file pointer resource returned by fopen() .

  • The return value is the number of bytes output.


Use scenarios

  • File download interface

  • Output of picture or video stream

  • Any scenario where files need to be sent to the client intact


Steps to implement file streaming using fpassthru

  1. Open the file <br> Use fopen() to open the file in binary mode to ensure that the transferred file is not affected by character encoding.

  2. Send the correct HTTP header <br> Send the corresponding Content-Type , Content-Length and Content-Disposition according to the file type (if downloaded files).

  3. Call fpassthru to output file stream <br> Export the file content directly to the client.

  4. Close file resources <br> Release resources to avoid resource leakage.


Complete sample code

 <?php
// File path
$filePath = '/path/to/your/file.zip';

// Determine whether the file exists
if (!file_exists($filePath)) {
    header("HTTP/1.1 404 Not Found");
    exit("File not found.");
}

// Open the file
$fp = fopen($filePath, 'rb');
if (!$fp) {
    header("HTTP/1.1 500 Internal Server Error");
    exit("Failed to open file.");
}

// Get file size
$fileSize = filesize($filePath);

// set up HTTP head,Tell the browser file type and size
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . $fileSize);
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Expires: 0');

// use fpassthru Output file content
fpassthru($fp);

// Close file resources
fclose($fp);
exit;
?>

Code description

  • fopen($filePath, 'rb') : Open the file in binary read-only mode.

  • The HTTP header set ensures that the browser recognizes the file type and size, and Content-Disposition specifies the default name of the downloaded file.

  • fpassthru($fp) will output all data from the current position of the file pointer to the end of the file directly.

  • Close the file handle and exit to ensure that no redundant content is output.


Things to note

  • If the file is large, fpassthru is an efficient way to transfer it because it will not read all files into memory.

  • Be sure to send the appropriate HTTP header before transferring to ensure that the browser handles the file correctly.

  • If the file path comes from user input, be sure to perform security verification to prevent security risks such as path crossing.

  • For download requirements that support breakpoint continuous transmission, additional HTTP_RANGE header is required, and this article will not explain in detail.


summary

Through the above steps, you can easily use PHP's fpassthru function to achieve efficient file streaming. It is suitable for all kinds of file download and streaming media output scenarios, with concise code and excellent performance.

If you need to build a file download interface or media streaming service, you might as well try fpassthru , which will make your code more concise and efficient.