1

因此,我正在尝试使用 FTP 将文件从本地服务器复制到远程服务器。问题是,我需要分块执行此操作。

到目前为止,根据我的研究,看起来通过在我的本地服务器上创建两个文件可能最容易做到这一点:要复制的文件和一个包含当前块的小型临时文件。然后,我应该简单地将该块与远程文件合并。

问题是,我无法附加文件。我无法弄清楚该ftp://协议是如何工作的,也找不到关于如何使用 cURL 进行操作的全面解释。我找到的最接近的是this,但我无法让它工作。

以下是我到目前为止所写的内容。我已经对其进行了评论,因此您可以浏览一下以了解想法,然后看看我卡在哪里-代码并不复杂。你建议我做什么?如何使用 FTP 将本地服务器上的文件附加到远程服务器上的文件?

<?php

// FTP credentials
$server = HIDDEN;
$username = HIDDEN;
$password = HIDDEN;

// Connect to FTP
$connection = ftp_connect($server) or die("Failed to connect to <b>$server</b>.");

// Login to FTP
if (!@ftp_login($connection, $username, $password))
{
    echo "Failed to login to <b>$server</b> as <b>$username</b>.";
}

// Destination file (where the copied file should go)
$destination = 'final.txt';

// The file on my server that we're copying (in chunks) to $destination.
$read = 'readme.txt';

// Current chunk of $read.
$temp = 'temp.tmp';

// If the file we're trying to copy exists...
if (file_exists($read))
{
    // Set a chunk size (this is tiny, but I'm testing
    // with tiny files just to make sure it works)
    $chunk_size = 4;

    // For reading through the file we want to copy to the FTP server.
    $read_handle = fopen($read, 'r');

    // For writing the chunk to its own file.
    $temp_handle = fopen($temp, 'w+');

    // Loop through $read until we reach the end of the file.
    while (!feof($read_handle))
    {
        // Read a chunk of the file we're copying.
        $chunk = fread($read_handle, $chunk_size);

        // Write that chunk to its own file.
        fwrite($temp_handle, $chunk);

        ////////////////////////////////////////////
        ////                                    ////
        ////       NOW WHAT?? HOW DO I          ////
        ////       WRITE / APPEND THAT          ////
        ////       CHUNK TO $destination?       ////
        ////                                    ////
        ////////////////////////////////////////////
    }
}

fclose($read_handle);
fclose($temp_handle);
ftp_close($ftp_connect);
?>
4

1 回答 1

0

首先,我认为您不需要创建 tmp 文件。您可以使用手册a中定义的“附加模式”( )或与标志一起使用附加到目标文件。file_put_contentsFILE_APPEND

file_put_contents 确实将文件名作为参数而不是文件句柄,因此它基本上fopen对您有用,这意味着如果您经常写入,它会fopen经常与使用文件句柄 a​​d 相比不太理想fwrite

<?php
// The URI of the remote file to be written to
$write = 'ftp://username1:password1@domain1.com/path/to/writeme.txt';

// The URI of the remote file to be read
$read = 'ftp://username2:password2@domain2.com/path/to/readme.txt';

if (file_exists($read)) // this will work over ftp too
{
    $chunk_size = 4;
    $read_handle = fopen($read, 'r');
    $write_handle = fopen($write, 'a');

    while (!feof($read_handle))
    {
        $chunk = fread($read_handle, $chunk_size);
        fwrite($write_handle, $chunk);
    }
}

fclose($read_handle);
fclose($write_handle);
?>

附带说明:PHP 具有流包装器,使 ftp 访问变得轻而易举,而无需使用 ftp 函数本身。

于 2012-06-29T18:38:08.790 回答