Home >Backend Development >PHP Tutorial >How to Download an FTP File Directly to the Browser in PHP Without Server Storage?

How to Download an FTP File Directly to the Browser in PHP Without Server Storage?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 06:27:30592browse

How to Download an FTP File Directly to the Browser in PHP Without Server Storage?

Download a File to the Browser from FTP without Server Storage or Redirection

In PHP scripts, fetching files from FTP servers is a common task. However, storing these files on the web server before sending them to the user's browser can be undesirable. This article explores how to download a file from an FTP server directly to the browser, bypassing server storage and avoiding redirects.

Original Code

The initial code retrieves an FTP file into memory using ftp_get() and ob_start():

<code class="php">public static function getFtpFileContents($conn_id , $file)
{
    ob_start();
    $result = ftp_get($conn_id, "php://output", $file, FTP_BINARY);
    $data = ob_get_contents();
    ob_end_clean();
    if ($resul)
        return $data;
    return null;
}</code>

Direct Stream to Browser

To stream the file directly to the browser without saving it, remove the output buffering:

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

Adding Content-Length Header

To include the Content-Length header, query the file size using ftp_size():

<code class="php">$conn_id = ftp_connect("ftp.example.com");
ftp_login($conn_id, "username", "password");
ftp_pasv($conn_id, true);

$file_path = "remote/path/file.zip";
$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 implement error handling as necessary. For more information on FTP file handling, refer to resources like "List and download clicked file from FTP."

The above is the detailed content of How to Download an FTP File Directly to the Browser in PHP Without Server Storage?. 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