如何使用PHP下载FTP后将文件移动到特定文件夹



有没有办法使用PHP中的FTP方法将文件移动到特定文件夹或声明特定文件夹以下载文件?

简而言之,我正在下载10,000 +文件,我希望它们进入我已经创建的某个文件夹。我正在使用FTP连接从我的脚本下载文件,并且我正在循环访问FTP服务器中的每个文件。它们都下载(这需要很长时间( - 我只需要声明一个特定的路径或将文件移动到文件夹中。

这是代码:

 function ftp_sync($dir, $conn_id){
   if($dir !== '.'){
     if(ftp_chdir($conn_id, $dir) === FALSE){
       echo 'Change directory failed: ' . $dir . PHP_EOL;
   return;
 }
 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, $conn_id);
 } else {
   ftp_get($conn_id, $file, $file, FTP_BINARY);
   //TODO: Download the files into a specific directory
 }
}
 ftp_chdir($conn_id, '..');
 chdir('..');
}
$ftp_server    = 'server';
$user          = 'user';
$password      = 'password';
$document_root = '/';
$sync_path     = 'Web_Images';
$conn_id = ftp_connect($ftp_server);
if ($conn_id) {
  $login_result = ftp_login($conn_id, $user, $password);
ftp_pasv($conn_id, true);
if ($login_result) {
    ftp_chdir($conn_id, $document_root);
    ftp_sync($sync_path, $conn_id);
    ftp_close($conn_id);
} else {
    echo 'login to server failed!' . PHP_EOL;
}
} else {
 echo 'connection to server failed!';
}
echo 'done.' . PHP_EOL;

默认情况下,ftp_get($conn_id, $file, $file, FTP_BINARY);应该能够将远程文件放置在您想要的任何位置,您只需在本地参数中指示该位置:

# Where ever you want to download local files to
$dir = __DIR__.'/my/specific/path/';
# See if directory exists, create if not
if(!is_dir($dir))
    mkdir($dir,0755,true);
# Saves the file(s) into the $dir folder with the same name as the remote file
ftp_get($conn_id, $dir.$file, $file, FTP_BINARY);

最新更新