Downloading Files from FTP Server to Browser with Content-Length Header
You can download a file directly to the user's browser without storing it on the server by removing the output buffering from the code.
<code class="php">ftp_get($conn_id, "php://output", $file, FTP_BINARY);</code>
To add the Content-Length header, you'll need to obtain the file size first 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 include error handling for a complete solution.
Additional Background
Refer to the resources below for further information on FTP file handling:
The above is the detailed content of How Can I Download Files from an FTP Server Directly to a Browser Using PHP?. For more information, please follow other related articles on the PHP Chinese website!