FTP 下载文件夹 php

FTP download folder with php

所以我想知道我可以从我的 FTP 服务器下载一个完整的文件夹,只需单击 link。当我必须从我的 FTP 服务器下载我的 .log 文件时,我会这样做:

首先我创建一个 link:

function FTP_download($id, $folder = ""){
    ?> <a href="ftp_download.php?folder=<?php echo $folder; ?>&id=<?php echo $id;?>&file=<?php echo $id.'.log'; ?>" download> Download full log </a> <?php
}

然后我调用下载器文件:

<?php
//Does GET exist
if (!isset($_GET['file'])) {
    echo"ERROR - loading log";
    return false;
}

//Define FTP variables
$ftp_server = "xxxx";
$ftp_user_name = "xxxx";
$ftp_user_pass = "xxxx";
$file = $_GET['file'];
$id = $_GET['id'];
$folder = $_GET['folder'];
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);


// Change dir to id folder
ftp_chdir($conn_id, $id);
// Change dir to logs
ftp_chdir($conn_id, $folder);

//Check if file exists
ftp_pasv($conn_id, true);
$list = ftp_nlist($conn_id, '');
if (!in_array($file, $list)) {
    return false;
}


// get the size of $file
$size = ftp_size($conn_id, $file);

//Create headers for force download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $size);

//Read file content
readfile('ftp://'.$ftp_user_name.':'.urlencode($ftp_user_pass).'@'.$ftp_server.'/'.$id.'/'.$folder.'/'.$file);
ftp_close($conn_id);
return true;
?>

点击 link,开始浏览器下载。

是否可以创建一个下载文件来下载整个文件夹,其中包含所有内容?

点赞下载 -> 'ftp://'.$ftp_user_name.':'.urlencode($ftp_user_pass).'@'.$ftp_server.'/'.$id.'/'.$folder

我会做的是下载 /tmp 目录中的所有文件,然后 然后将它们全部压缩到一个存档中。 然后可以将该文件作为响应流式传输。

确保您的 tmp 目录已被清除,通常 php 会在请求完成后自行清除 see here

PHP ZipArchive

如果您想在单个请求中(而不是在一个文件夹中)下载所有文件。
当使用 'Content-Disposition' 值作为文件内容之间的分隔符时,这可能会起作用。 我无法自信地向您解释您需要什么。 也许谷歌搜索 'mulipart form request' 会给你一个教程。

至于创建一个直接文件夹作为响应,我从未见过这样的功能,我认为这不可能。

在我看来 Zip 是最好的选择,因为它应该得到足够广泛的支持, 并保持你的文件夹完好无损,我认为你想保留。