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.
-----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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With