1

in my php restful api running on a heroku dyno, since my api accept user to upload files view ($_FILES) -form post- i need to forward the uploaded files to my ftp server to persist them since heroku does not have storage.

i googled around to find best way to achieve this and found two methods

code example show both methods

// common code:
$tmp_file_path = $_FILES['image']['tmp_name'];
$raw_filename = explode('.',$_FILES['image']['name']);
$extention = array_pop($raw_filename);
$filename = md5(implode('.',$raw_filename)).$extention;

// 1st: ftp_put_content;
$content = file_get_contents($tmp_file_path);
// additional stream is required as per http://php.net/manual/en/function.file-put-contents.php#96217
$stream = stream_context_create(['ftp' => ['overwrite' => true]]); 
$upload_success = file_put_content('ftp://username:password@ftpserver.com/'+$filename, $content, 0, $stream);

// 2nd: ftp_put
$conn_id = ftp_connect("ftp.simpleinformatics.com");
$login_result = ftp_login($conn_id, "username", "password");
ftp_pasv($conn_id, true); //for somereason my ftp serve requires this !
if (!$conn_id OR !$login_result) $upload_success = false;
$ftp_upload_success = ftp_put($conn_id,'/'.$filename, $tmp_file_path);

echo "file_put_content" . ($upload_success ? "upload success" : 'file upload failed');

echo "ftp_put" . ($ftp_upload_success ? "upload success" : 'file upload failed');

i test the two methods against my ftp server and both works yet i worried about reliability, there is very few documentation about details of how two methods works so i'm not sure of couple things.

  1. can i use file_put_content flags when putting to ftp file ? like FILE_APPEND or LOCK_EX ?
  2. what will happen if uploading to a folder that does not yet exists ?
  3. which method is more reliable and less prone to fail ?
  4. although file_put_contents is less verbose, we need to read file content first before writing, can this cause a memory problem ?
Zalaboza
  • 8,899
  • 16
  • 77
  • 142
  • 1
    Didn't read most of the post, but going by the title, I'd say `ftp_*` functions are more reliable as file wrappers for these protocols can be disabled. – Jonnix Nov 08 '16 at 12:26
  • @JonStirling does ftp_* handle file_append/file locking/ creating directories if not exists ? – Zalaboza Nov 08 '16 at 12:28

1 Answers1

0
  1. FTP URL wrapper supports appending as of PHP 5:
    https://www.php.net/manual/en/wrappers.ftp.php#refsect1-wrappers.ftp-options
  2. FTP folder is not created, using any method. You have to take care of that yourself.
  3. Too broad.
  4. Unclear.
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992