[英]PHP - Merging files with FTP
因此,我正在嘗試使用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);
?>
首先,我認為您不需要創建tmp文件。 您可以使用手冊中定義的“追加模式”( a
)或使用帶有FILE_APPEND
標志的file_put_contents
追加到目標文件。
file_put_contents確實將文件名作為參數而不是文件句柄,因此它基本上會為您fopen
,這意味着,如果您頻繁寫入,它將經常fopen
,這與使用文件句柄ad 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函數本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.