将内存中的数据传输到FTP服务器而不使用中间文件 [英] Transfer in-memory data to FTP server without using intermediate file

查看:104
本文介绍了将内存中的数据传输到FTP服务器而不使用中间文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JSON数据,我用PHP的 json_encode()编码它,它看起来像这样:

  {
site:site1,
nbrSicEnt:85,
}



我想要将数据直接作为文件写入FTP服务器。



<为了安全起见,我不希望在将文件发送到FTP服务器之前先在本地创建文件,我希望它可以随时创建。因此,例如,不要使用 tmpfile()当我阅读的php文档时, ftp_put

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

需要创建一个本地文件( string $ local_file ),然后将它写入远程文件。



我正在寻找一种直接写入进入remote_file。我怎样才能使用PHP?

解决方案

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)

这篇关于将内存中的数据传输到FTP服务器而不使用中间文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆