为了账号安全,请及时绑定邮箱和手机立即绑定

PHP FTP - 下载特定目录中的文件而不是根目录

PHP FTP - 下载特定目录中的文件而不是根目录

PHP
繁星淼淼 2023-10-15 17:21:02
我在 /Users/John/Site/Code/pdfsync.php 有一个 php 脚本在我的脚本中,我连接到 FTP,并递归下载文件,但是它在 /Users/John/Site/ 创建文件夹并下载文件,但我似乎不知道如何获取这些文件下载到特定位置。假设当我运行脚本时,我希望它创建一个 PDF 文件夹,因此所有文件都在 /Users/John/Site/Code/PDF/ 下载,不知道如何实现这一点。$ftp_server = 'test.fr';$ftp_user_name = 'test';$ftp_user_pass = 'test';$server = 'test.fr';// 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);if ((!$conn_id) || (!$login_result))    die("FTP Connection Failed");ftp_sync (".");echo "Done";ftp_close($conn_id);function ftp_sync ($dir) {    global $conn_id;    if ($dir != ".") {        if (ftp_chdir($conn_id, $dir) == false) {            echo ("Change Dir Failed: $dir<BR>\r\n");            return;        }        if (!(is_dir($dir)))            mkdir($dir);        chdir ($dir);    }    $contents = ftp_nlist($conn_id, ".");    foreach ($contents as $file) {        if ($file == '.' || $file == '..')            continue;        if (@ftp_chdir($conn_id, $file)) {            ftp_chdir ($conn_id, "..");            ftp_sync ($file);        }        else            ftp_get($conn_id, $file, $file, FTP_BINARY);    }    ftp_chdir ($conn_id, "..");    chdir ("..");}
查看完整描述

2 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

您可以使用这个库非常轻松地做到这一点:

代码 :

$connection = new FtpConnection('host', 'username', 'password');


$client = new FtpClient($connection);


if (asyncDownload('Users/John/Site/Code/PDF', '.')) {

    echo 'Done!';

}


function syncDownload($localDir, $remoteDir)

{

    global $client;

    

    if (!is_dir($localDir)) {

        mkdir($localDir);

    }

    

    /**

     * listDirectoryDetails method will recursively gets all the files with

     * their details within the giving directory.

     */

    $files = $client->listDirectoryDetails($dir, true);

    

    foreach($files as $file) {

        $client->download($file['path'], $localDir . '/' . $file['name'], true, FtpWrapper::BINARY);

    }

    

    return true;

}


查看完整回答
反对 回复 2023-10-15
?
倚天杖

TA贡献1828条经验 获得超3个赞

根据代码的工作方式,最简单的解决方案是在调用之前将当前本地工作目录更改为目标路径ftp_sync:


chdir("/Users/John/Site/Code/PDF/");

ftp_sync (".");


查看完整回答
反对 回复 2023-10-15
  • 2 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信