I want to give my users the option to download files from their unique directory on a remote FTP server, however some of these are incredibly large in size. I have tried using FileSaver.js but this struggles with large files as I have to read them from the remote server to the local web-server first, then save them to the client. The alternative StreamSaver.js is a better option as it supports chunking, however it has little browser support.
Using the readfile in PHP works perfectly, where it streams the download to the client as it reads the data into memory. The problem is that the URL its pulling from contains FTP credentials, thus I don't want to link directly to it.
Is there any option that would allow me to provide them with some type of a "Download" button and still make use of the following code?
$file_url = 'ftp://username:password@124.23.148.103/124.23.148.103 port 25665/server.jar';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
You can use an html <form>
element at client side
<form action="download.php">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
File name: <input type="text" name="filename"><br>
<input type="submit" value="Download">
</form>
$file_url = "ftp://"
. $_GET["username"]
. ":"
. $_GET["password"]
. "@124.23.148.103/124.23.148.103 port 25665/"
. $_GET["filename"];
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
It mean you want PHP read file from FTP and stream it to your client. You can use PHP FTP
function, and you also can read the file as output buffer instead save it first to PHP Server.
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
$conn_id = ftp_connect(124.23.148.103);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to download file and stream it without save it on php server
if (!ftp_get($conn_id, "php://output", $server_file, FTP_BINARY)) {
echo "There was a problem when reading file
";
}
ftp_close($conn_id);