Transfer in-memory data to FTP server without usin

2019-01-07 21:45发布

问题:

I am having some JSON data that I encoded it with PHP's json_encode(), it looks like this:

{
    "site": "site1",
    "nbrSicEnt": 85,
}

What I want to do is to write the data directly as a file onto an FTP server.

For security reasons, I don't want the file to be created locally first before sending it to the FTP server, I want it to be created on the fly. So without using tmpfile() for example.

When I read the php documentations for ftp_put:

bool ftp_put ( resource $ftp_stream , string $remote_file , 
               string $local_file , int $mode [, int $startpos = 0 ] )

Ones needs to create a local file (string $local_file) before writing it to the remote file.

I am looking for a way to directly write into the remote_file. How can I do that using PHP?

回答1:

The file_put_contents is the easiest solution:

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

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


If you need greater control over the writting (transfer mode, passive mode, offset, reading limit, etc), 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, $contents);
rewind($h);

ftp_fput($conn_id, '/path/to/file', $h, FTP_BINARY, 0);

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

(add error handling)


Or you can open/create the file directly on the FTP server. That's particularly useful, if the file is large, as you won't have keep whole contents in memory.

See Generate CSV file on an external FTP server in PHP.



回答2:

According to Can you append lines to a remote file using ftp_put() or something similar? and Stream FTP Upload with PHP? you should be able to do something using either CURL or PHP's FTP wrappers using file_put_contents().

$data = json_encode($object);
file_put_contents("ftp://user:pass@host/dir/file.ext", $data, FILE_APPEND);


标签: php ftp