PHP - ftp_put + Copy Entire Folder Structure

2019-03-17 03:56发布

问题:

I'm trying to create an FTP script that will copy a local folder structure upto an FTP point. Basically to update a website.

I have been testing the following code (have changed the user/pass/domain) but the connection doesn't fail and appears to be working.

   $server = 'ftp.domainname.co';
   $ftp_user_name = 'user';
   $ftp_user_pass = 'pass';
   $dest = '.';
   $source = '.';
   $mode = 'FTP_ASCII';


   $connection = ftp_connect($server);

   $login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);

   if (!$connection || !$login) { die('Connection attempt failed!'); }

   $upload = ftp_put($connection, $dest, $source, $mode);

   if (!$upload) { echo 'FTP upload failed!'; }

   ftp_close($connection); 

I'm confident the point that is breaking is the ftp_put line. My questions are:

  1. Can ftp_put upload an entire directory structure with files etc or is this just to upload one file at a time? Is there a different command I should be using?

  2. I think I have something wrong with these variables:

        $dest = '.';
        $source = '.';
        $mode = 'FTP_ASCII';
    

I believe mode is correct.

$dest - this is just the root of the ftp server being ftp.domainname.co - should I put the ftp server name or what goes here.

$source - this is a the current local path - I've also tried the full C:\etc path.

I get this error: Warning: ftp_put() expects parameter 4 to be long

any help would be great.

thx

回答1:

It is not working because it is expecting a file, not a directory. PHP manual for ftp_put has some code examples for recursive file uploads posted by commenters.

Here is one of them (note that it requires a full path):

function ftp_putAll($conn_id, $src_dir, $dst_dir) {
    $d = dir($src_dir);
    while($file = $d->read()) { // do this for each file in the directory
        if ($file != "." && $file != "..") { // to prevent an infinite loop
            if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
                if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
                    ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
                }
                ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
            } else {
                $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
            }
        }
    }
    $d->close();
}


回答2:

Warning: ftp_put() expects parameter 4 to be long

Well, to me it seems quite obvious: parameter 4 needs to be 'long' (or: a number). In this case it can also be a CONSTANT that represents that number, such as ftp_put(x, y, z, FTP_ASCII). Not with quotes ('), like you did it: ftp_put(x, y, z, 'FTP_ASCII')



标签: php ftp