开发者

Can you append lines to a remote file using ftp_put() or something similar?

开发者 https://www.devze.com 2023-03-31 19:01 出处:网络
Here\'s the situation... I have two servers, server 1 and server 2. server 1 downloads a csv file from server 2, deletes it off server 2, reads lines from it and does some processing.

Here's the situation... I have two servers, server 1 and server 2. server 1 downloads a csv file from server 2, deletes it off server 2, reads lines from it and does some processing.

While it is processing, the file on server 2 can be re-created or changed, add开发者_运维知识库ing more lines. After it is done processing, server 1 needs to upload the file back to server 2.

However, ftp_put() will completely overwrite the file on server 2. What I really want to do is append to the file on server 2 and not overwrite it. Is there any way to do this?


Have you tried file_put_contents with the FILE_APPEND flag?


Curl support appending for FTP:

curl_setopt($ch, CURLOPT_FTPAPPEND, TRUE ); // APPEND FLAG

This might be what you're looking for. Are you familiar with curl?

The other option is to use ftp:// / ftps:// streams, since PHP 5 they allow appending. See ftp://; ftps:// Docs. Might be easier to access.


As shown in other answer, file_put_contents with FILE_APPEND flag is the easiest solution to append a chunk to the end of a remote file:

file_put_contents('ftp://username:pa‌​ssword@hostname/path/to/file', $chunk, FILE_APPEND);

If it does not work, it's probably because you do not have URL wrappers enabled in PHP.


Though, if you actually have a matching local copy of a file, just with the new contents appended, it's easier to use a "hidden" feature of the ftp_put, the FTP_AUTORESUME:

$conn_id = ftp_connect('hostname');

ftp_login($conn_id, 'username', 'password');
ftp_pasv($conn_id, true);

$remote_path = '/path/to/file';
$local_path = 'file';
ftp_put($conn_id, $remote_path, $local_file, FTP_BINARY, FTP_AUTORESUME);

ftp_close($conn_id);

(add error handling)


If you do not have a matching local file, i.e. you are uploading a chunk of contents from memory, and you need a greater control over the writing (transfer mode, passive mode, etc), than you get with the file_put_contents, use the ftp_fput with a handle to the php://temp (or the php://memory) stream:

$conn_id = ftp_connect('hostname');

ftp_login($conn_id, 'username', 'password');
ftp_pasv($conn_id, true);

$h = fopen('php://temp', 'r+');
fwrite($h, $chunk);
rewind($h);

// prevent ftp_fput from seeking local "file" ($h)
ftp_set_option($conn_id, FTP_AUTOSEEK, false);

$remote_path = '/path/to/file';
$size = ftp_size($conn_id, $remote_path);
$r = ftp_fput($conn_id, $remote_path, $h, FTP_BINARY, $size);

fclose($h);
ftp_close($conn_id);

(again, add error handling)

0

精彩评论

暂无评论...
验证码 换一张
取 消