Put a file on FTP site with contents from string variable (no local file)

This may be no ultimate solution but I guess is still better than the original approach:

You can avoid temporary files on the file system by using a PHP memory stream. It basically is a file handle wrapper which (behind the scenes) uses no actual file but instead some chunk of memory.

So virtually you still use a file handle (so ftp_fput is happy), but no actual file (so no file is written to the disk and the overhead is kept minimal).

$tmpfile = fopen('php://memory', 'r+');
fputs($tmpfile, $content);
rewind($tmpfile); // or fseek

Note that when uploading multiple files, you can further minimize overhead by reusing the same file handle for all files (unless you parallelize the procedure, of course). In this case, also rewind the file after ftp_fput as well as truncate it using ftruncate($tmpfile, 0).


With no local file involved (ftp_fput):

$stream = fopen('php://memory','r+');
fwrite($stream, $newFileContent);
rewind($stream);

$success = ftp_fput($connectionId, "remoteFileName", $stream, FTP_BINARY);

fclose($stream);

Tags:

Php

Ftp