且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将内存中的数据传输到FTP服务器而不使用中间文件

更新时间:2022-11-06 20:40:22

file_put_contents 是最简单的解决方案:

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

如果不起作用,可能是因为您没有在PHP中启用URL封装器




如果您需要更好地控制写入(传输模式,被动模式,偏移量,读取限制等),请使用 ftp_fput php:// temp (或 php:// memory )流

  $ conn_id = ftp_connect('hostname'); 

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

$ h = fopen('php:// temp','r +');
fwrite($ h,$ contents);
倒带($ h);

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

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

(添加错误处理)

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?

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');

$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)