FTP file upload example


 / Published in: PHP
 

URL: http://www.jonasjohn.de/snippets/php/ftp-example.htm

Shows how to upload a single file to a FTP server.

  1. // FTP access parameters:
  2. $host = 'ftp.example.org';
  3. $usr = 'example_user';
  4. $pwd = 'example_password';
  5.  
  6. // file to upload:
  7. $local_file = './example.txt';
  8. $ftp_path = '/data/example.txt';
  9.  
  10. // connect to FTP server (port 21)
  11. $conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
  12.  
  13. // send access parameters
  14. ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
  15.  
  16. // turn on passive mode transfers (some servers need this)
  17. // ftp_pasv ($conn_id, true);
  18.  
  19. // perform file upload
  20. $upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
  21.  
  22. // check upload status:
  23. print (!$upload) ? 'Cannot upload' : 'Upload complete';
  24. print "\n";
  25.  
  26. /*
  27. ** Chmod the file (just as example)
  28. */
  29.  
  30. // If you are using PHP4 then you need to use this code:
  31. // (because the "ftp_chmod" command is just available in PHP5+)
  32. if (!function_exists('ftp_chmod')) {
  33. function ftp_chmod($ftp_stream, $mode, $filename){
  34. return ftp_site($ftp_stream, sprintf('CHMOD %o %s', $mode, $filename));
  35. }
  36. }
  37.  
  38. // try to chmod the new file to 666 (writeable)
  39. if (ftp_chmod($conn_id, 0666, $ftp_path) !== false) {
  40. print $ftp_path . " chmoded successfully to 666\n";
  41. } else {
  42. print "could not chmod $file\n";
  43. }
  44.  
  45. // close the FTP stream
  46. ftp_close($conn_id);

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: vatsav on August 30, 2009

excellent... this is the one for which i'm searching the whole internet !!! thanks a tonne

Posted By: ren on November 14, 2009

haven't tested this but according to the link provided line 23 has a typo

// check upload status: print (!$upload) ? 'Cannot upload' : 'Upload complete'; print "\n";

Posted By: kuma2525 on March 12, 2011

it just missing a ?

Posted By: fackz on April 19, 2011

Yes, it's missing a ? on line 23...I just don't know how to edit the snippet. :(

Posted By: hxseven on October 25, 2011

Fixed the typo, thanks!

Posted By: jordanfung on April 26, 2014

I want to ask if the ./example.txt in line 7 is on the users' computer or in the server? If it is in the user's computer, what is the path "./" in the user'computer?

Posted By: jordanfung on April 26, 2014

I want to ask if the ./example.txt in line 7 is on the users' computer or in the server? If it is in the user's computer, what is the path "./" in the user'computer?

You need to login to post a comment.