Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

ftp

I want to upload a file to an FTP server, but the file content is held in a variable, not in an actual local file. I want to avoid using a file; this is to avoid security risks when dealing with sensitive data on a (possibly) not-so-secure system(*), as well as to minimize the (already low) overhead of file handling.

But PHP's FTP API only offers uploading files from local files via the function ftp_put or (when the file is already opened as a file handle) ftp_fput.

Currently, I use this function with a temporary file in which I write the contents before the upload:

$tmpfile = tmpfile();
fwrite($tmpfile, $content);
fseek($tmpfile, 0);
ftp_fput($ftp, $filename, $tmpfile, FTP_BINARY);

Is there a simpler way without using files on the local (PHP) site at all?

There is ftp_raw which can be used to send arbitrary commands, so I could issue the PUT command manually, however I don't see a way to manually write the data on the data channel...

I don't know if it is important, but the FTP connection is secured with SSL (ftp_ssl_connect).


(*) Consider the scenario where an attacker has read-only control over the entire file system.

like image 216
leemes Avatar asked Jun 26 '15 14:06

leemes


2 Answers

-----FTP PUT contents (php 7.0) ---

$tmpFile = tmpfile();

fwrite($tmpFile, $contents);
rewind($tmpFile);

$tmpMetaData = stream_get_meta_data($tmpFile);

if (ftp_put($ftpObj, $remoteFile, $tmpMetaData['uri'], FTP_ASCII)) {
    echo "success";
} else {
    echo "fail";
}

fclose($tmpFile);
like image 169
2 revs, 2 users 80% Avatar answered Jan 04 '23 10:01

2 revs, 2 users 80%


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);
like image 45
David M Avatar answered Jan 04 '23 09:01

David M