Transferring data in memory to an FTP server without using an intermediate file

I have some JSON data that I encoded using PHP json_encode() , it looks like this:

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

What I want to do is write the data directly as a file to 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. Thus, without using tmpfile() for example.

When I read the php documentation for ftp_put :

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

To write a file to a remote file, you must create a local file ( string $local_file ).

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

+1
source share
2 answers

file_put_contents is the easiest solution:

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

If this does not work, this may be due to the fact that there are no URL handlers in PHP .


If you need more control over the text (transmission mode, passive mode, offset, reading limit, etc.), use ftp_fput with the ftp_fput descriptor php://temp (or php://memory ) :

 $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. This is especially useful if the file is large, since you will not store all the contents in memory.

See Creating a CSV file on an external FTP server in PHP .

+2
source

According to Can you add lines to the remote file using ftp_put () or something like that? and FTP upload stream using PHP? you can do something using the file_put_contents() or PHP FTP framework using file_put_contents() .

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

All Articles