How to Directly Download Files from FTP to User\'s Browser in PHP without Disk Storage?

Susan Sarandon
Release: 2024-11-02 12:03:30
Original
486 people have browsed it

How to Directly Download Files from FTP to User's Browser in PHP without Disk Storage?

Downloading Files via PHP Script from FTP to Browser without Disk Storage

Using PHP, files can be efficiently retrieved from FTP servers. However, what if the objective is to directly deliver the file to the user's browser, bypassing local disk storage?

Method Without Output Buffering:

To achieve this, simply remove the output buffering functions (ob_start() and its counterparts):

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

Adding Content-Length Header:

To include the Content-Length header, follow these steps:

  1. Query the file size using ftp_size().
  2. Set HTTP headers for content type, disposition, and length.
  3. Use ftp_get() to retrieve the file directly to the browser.

Code Example:

<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>
Copy after login

Additional Notes:

  • Remember to handle errors properly.
  • For a comprehensive overview of handling FTP files, refer to the "List and Download Clicked File from FTP" documentation.

The above is the detailed content of How to Directly Download Files from FTP to User\'s Browser in PHP without Disk Storage?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!