Home  >  Article  >  Backend Development  >  How Can I Download Files from an FTP Server Directly to a Browser Using PHP?

How Can I Download Files from an FTP Server Directly to a Browser Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 14:43:301004browse

How Can I Download Files from an FTP Server Directly to a Browser Using PHP?

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:

  • List and Download Clicked Files from FTP
  • PHP FTP Functions: ftp_get

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!

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