通过 PHP FTP 上传整个目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/927341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:21:18  来源:igfitidea点击:

Upload Entire Directory via PHP FTP

phpuploadftpdirectory

提问by Joel Drapper

I'm trying to write a script that will upload the entire contents of a directory stored on my server to other servers via ftp.

我正在尝试编写一个脚本,该脚本将通过 ftp 将存储在我的服务器上的目录的全部内容上传到其他服务器。

I've been reading through the documentation on www.php.net, but can't seem to find a way to upload more then one file at a time.

我一直在阅读www.php.net 上文档,但似乎无法找到一次上传多个文件的方法。

Is there a way to do this, or is there a script that will index that directory and create an array of files to upload?

有没有办法做到这一点,或者是否有一个脚本可以索引该目录并创建要上传的文件数组?

Thanks in advance for your help!

在此先感谢您的帮助!

回答by Frank Farmer

Once you have a connection open, uploading the contents of a directory serially is simple:

打开连接后,串行上传目录的内容很简单:

foreach (glob("/directory/to/upload/*.*") as $filename)
    ftp_put($ftp_stream, basename($filename) , $filename, FTP_BINARY);

Uploading all files in parallel would be more difficult.

并行上传所有文件会更加困难。

回答by Xackery

So, I took @iYETER's code, and wrapped it as a class object.

因此,我采用了@iYETER 的代码,并将其包装为一个类对象。

You can call this code by these lines:

您可以通过以下几行调用此代码:

$ftp = new FtpNew("hostname");

$ftpSession = $ftp->login("username", "password");

if (!$ftpSession) die("Failed to connect.");

$errorList = $ftp->send_recursive_directory("/local/dir/", "/remote/dir/");
print_r($errorList);

$ftp->disconnect();

It recursively crawls local dir, and places it on remote dir relative. If it hits any errors, it creates a array hierarchy of every file and their exception code (I only capture 2 so far, if it's another error, it throws it default route for now)

它递归地抓取本地目录,并将其放置在远程目录相对位置上。如果遇到任何错误,它会创建每个文件及其异常代码的数组层次结构(到目前为止我只捕获了 2 个,如果是另一个错误,它现在会抛出默认路由)

The class this is wrapped into:

这被包装成的类:

<?php
//Thanks for iYETER on http://stackoverflow.com/questions/927341/upload-entire-directory-via-php-ftp

class FtpNew {
private $connectionID;
private $ftpSession = false;
private $blackList = array('.', '..', 'Thumbs.db');
public function __construct($ftpHost = "") {
    if ($ftpHost != "") $this->connectionID = ftp_connect($ftpHost);
}

public function __destruct() {
    $this->disconnect();
}

public function connect($ftpHost) {     
    $this->disconnect();
    $this->connectionID = ftp_connect($ftpHost);
    return $this->connectionID;
}

public function login($ftpUser, $ftpPass) {
    if (!$this->connectionID) throw new Exception("Connection not established.", -1);
    $this->ftpSession = ftp_login($this->connectionID, $ftpUser, $ftpPass);
    return $this->ftpSession;
}

public function disconnect() {
    if (isset($this->connectionID)) {
        ftp_close($this->connectionID);
        unset($this->connectionID);
    }
}

public function send_recursive_directory($localPath, $remotePath) {
    return $this->recurse_directory($localPath, $localPath, $remotePath);
}

private function recurse_directory($rootPath, $localPath, $remotePath) {
    $errorList = array();
    if (!is_dir($localPath)) throw new Exception("Invalid directory: $localPath");
    chdir($localPath);
    $directory = opendir(".");
    while ($file = readdir($directory)) {
        if (in_array($file, $this->blackList)) continue;
        if (is_dir($file)) {
            $errorList["$remotePath/$file"] = $this->make_directory("$remotePath/$file");
            $errorList[] = $this->recurse_directory($rootPath, "$localPath/$file", "$remotePath/$file");
            chdir($localPath);
        } else {
            $errorList["$remotePath/$file"] = $this->put_file("$localPath/$file", "$remotePath/$file");
        }
    }
    return $errorList;
}

public function make_directory($remotePath) {
    $error = "";
    try {
        ftp_mkdir($this->connectionID, $remotePath);
    } catch (Exception $e) {
        if ($e->getCode() == 2) $error = $e->getMessage(); 
    }
    return $error;
}

public function put_file($localPath, $remotePath) {
    $error = "";
    try {
        ftp_put($this->connectionID, $remotePath, $localPath, FTP_BINARY); 
    } catch (Exception $e) {
        if ($e->getCode() == 2) $error = $e->getMessage(); 
    }
    return $error;
}
}

回答by alanquillin

Do it in a loop, iterating through all the files in the folder

循环执行,遍历文件夹中的所有文件

$servername = $GLOBALS["servername"];
    $ftpUser = $GLOBALS["ftpUser"];
    $ftpPass = $GLOBALS["ftpPass"];
$conn_id = ftp_connect($servername) or die("<p style=\"color:red\">Error connecting to $servername </p>");

if(ftp_login($conn_id, $ftpUser, $ftpPass))
{
    $dir_handle = @opendir($path) or die("Error opening $path");

         while ($file = readdir($dir_handle)) {
            ftp_put($conn_id, PATH_TO_REMOTE_FILE, $file)
        }
}

回答by iYETER

I coded it, the script uploads whole folder with it's subfolders and files.

我对它进行了编码,脚本上传了整个文件夹及其子文件夹和文件。

I hope it will help you.

我希望它会帮助你。

<?php 
ob_start(); 
set_time_limit(0); 
//r10.net fatal

$anadizin="uploadedeceginizdizin"; //this is the folder that you want to upload with all subfolder and files of it.

$ftpsunucu="domain.com"; //ftp domain name
$ftpusername="ftpuser";  //ftp user name 
$ftppass="ftppass"; //ftp passowrd
$ftpdizin="/public_html"; //ftp main folder





$arkadaslarlabardaydik = ftp_connect($ftpsunucu); 
$ictikguldukeglendik = ftp_login($arkadaslarlabardaydik, $ftpusername, $ftppass); 

if((!$arkadaslarlabardaydik) || (!$ictikguldukeglendik))  
{ 
  echo "cant connect!"; 
  die(); 
} 


function klasoruoku($dizinadi) 
{ 
  global $nerdeyiz,$fulldizin,$ftpdizin,$arkadaslarlabardaydik,$ftpdizin; 

  chdir($dizinadi."\"); 
  $dizin = opendir("."); 

  while($bilgi=readdir($dizin))  
  { 
    if ($bilgi!='.' and $bilgi!='..' and $bilgi!="Thumbs.db") 
    {  
        $tamyol="$dizinadi\$bilgi"; 

        $lokalkla=str_replace("".$nerdeyiz."\","",$dizinadi).""; 
        $lokaldosya="$lokalkla\$bilgi"; 
        $ftpyeyolla=str_replace(array("\\","\"),array("/","/"),"$ftpdizin\".str_replace("".$fulldizin."","",$dizinadi)."\$bilgi"); 

        if(!is_dir($bilgi)) 
        { 
          $yükleme = ftp_put($arkadaslarlabardaydik, $ftpyeyolla, $tamyol, FTP_BINARY); 

          if (!$yükleme)  
          { 
              echo "$lokaldosya <font color=red>uploaded</font>"; echo "<br>";  fls(); 
          }  
          else  
          { 
              echo "$lokaldosya <font color=green>not uploaded</font>"; echo "<br>"; fls(); 
          } 
        } 
        else 
        {  
          ftp_mkdir($arkadaslarlabardaydik, $ftpyeyolla); 
          klasoruoku("$dizinadi\$bilgi"); 
          chdir($dizinadi."\"); 
          fls(); 
        } 
    } 
  } 
  closedir ($dizin); 
} 

function fls() 
{ 
    ob_end_flush(); 
    ob_flush(); 
    flush(); 
    ob_start(); 
} 

$nerdeyiz=getcwd(); 
$fulldizin=$nerdeyiz."\$anadizin"; 
klasoruoku($fulldizin); 
ftp_close($arkadaslarlabardaydik); 

?>

回答by Boris Guéry

If you want to have multiple files uploaded at once, you'll need to use thread or fork.

如果您想一次上传多个文件,则需要使用 thread 或 fork。

I'm not sure of a Thread implentation in PHP, but you should take a look at the PHP SPLand/or PEAR

我不确定 PHP 中的线程实现,但你应该看看PHP SPL和/或PEAR

Edit:Thanks to Frank Farmer to let me know that there was a fork() function in PHP known as pcntl_fork()

编辑:感谢 Frank Farmer 让我知道 PHP 中有一个 fork() 函数,称为pcntl_fork()

You'll also have to get the whole content directory recursively to be able to upload all the file for a given directory.

您还必须递归获取整个内容目录才能上传给定目录的所有文件。