Home >Backend Development >PHP Tutorial >How to Stream FTP Files Directly to the Browser Without Saving Locally?

How to Stream FTP Files Directly to the Browser Without Saving Locally?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 19:01:30398browse

How to Stream FTP Files Directly to the Browser Without Saving Locally?

Download File from FTP Server to Browser without Saving Locally

This question seeks an efficient way to retrieve a file from an FTP server and send it directly to the user's browser, bypassing local storage and redirects.

The provided PHP function, getFtpFileContents, fetches the file into memory but requires subsequent manual steps to send it to the browser. To remove the need for intermediate storage, simply remove the output buffering code:

<code class="php">ftp_get($conn_id, "php://output", $file, FTP_BINARY);</code>

If you wish to include the Content-Length header, it is necessary to query the file size first:

<code class="php">$size = ftp_size($conn_id, $file_path);

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . basename($file_path));
header("Content-Length: $size"); 

ftp_get($conn_id, "php://output", $file_path, FTP_BINARY);</code>

Remember to incorporate error handling into your code for robust operation.

The above is the detailed content of How to Stream FTP Files Directly to the Browser Without Saving Locally?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn