Download File Via PHP Script from Ftp Server to Browser With Content-Length Header Without Storing the File on the Web Server

Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server

Just remove the output buffering (ob_start() and the others).

Use just this:

ftp_get($conn_id, "php://output", $file, FTP_BINARY);

Though if you want to add Content-Length header, you have to query file size first using ftp_size:

$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);

(add error handling)


For more broad background, see:

List and download clicked file from FTP

List and download clicked file from FTP

Your link in the generated <a> tag points back to the web server, which does not contain the linked file.

What you need to do is to link to a PHP script, giving it a name of the file to download. The script will then download the file from an FTP server and pass the downloaded file back to the user (to the webbrowser).

echo "<a href=\"download.php?file=".urlencode($file)."\">".htmlspecialchars($file)."</a>";

A very trivial version of the download.php script:

<?

header('Content-Type: application/octet-stream');

echo file_get_contents('ftp://username:password@ftp.example.com/path/' . $_GET["file"]);

The download.php script uses FTP URL wrappers. If that's not allowed on your web server, you have to go the harder way with FTP functions. See
PHP: How do I read a file from FTP server into a variable?


Though for a really correct solution, you should provide some HTTP headers related to the file, like Content-Length, Content-Type and Content-Disposition.

Also the above trivial example will first download whole file from the FTP server to the webserver. And only then it will start streaming it to the user (webbrowser). What is a waste of time and also of a memory on the webserver.

For a better solution, see Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server.

You may also want to autodetect Content-Type, unless all your files are of the same type.


A related question about implementing an FTP upload with a webpage:

Displaying recently uploaded images from remote FTP server in PHP

How to delete file after access it with ajax request?

There's no need for you to save the file to a temporary physical file on your web server.

You can send it directly to the client.

See Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server.



Related Topics



Leave a reply



Submit