How to stream a large file using PHP?

Spread the love

Sometimes, we want to stream a large file using PHP.

In this article, we’ll look at how to stream a large file using PHP.

How to stream a large file using PHP?

To stream a large file using PHP, we can use the fpassthru function.

For instance, we write

$path = "path/to/file";
$public_name = basename($path);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $path);

header("Content-Disposition: attachment; filename=$public_name;");
header("Content-Type: $mime_type");
header("Content-Length: " . filesize($path));

$fp = fopen($path, "rb");
fpassthru($fp);
exit();

to call header to set the header values for the file.

We set Content-Type to $mime_type.

And we Content-Length to the file size that we get from $filesize.

$public_name is the public file name, which we use as the value of filename.

Then we open the file from the $path with fopen.

Next we call fpassthru with $fp to stream the file.

Once we’re done streaming, we call exit.

Conclusion

To stream a large file using PHP, we can use the fpassthru function.

Leave a Reply

Your email address will not be published.