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.
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>
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>
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!