BC Tech : Free Tutorials and More Advertisement
Main
Wednesday, 07 January 2009
 
 
Transfer Files Between Servers Print E-mail
Tutorials / FAQs - Programming
If you've ever switched webhosts, you know how terribly frustrating it can be. One of the most painful tasks is uploading all the content to your new server from a slow home Internet connection. You can remove this bottleneck by transferring files between servers directly. Here I show you how to interact with FTP through PHP.

Recently someone on a forum I visit asked for tips about this: "I need a script that is capable of making a simple site mirroring, that is, to transfer one or more files directly between two servers without downloading them first to my local computer."

Just swap out the comments if your situation calls for a file pull rather than a file push. 

FTP through PHP
  1. <?php
  2.  
  3. $ftp_server = 'ftp.domain.com';
  4. $ftp_user_name = 'ftpuser';
  5. $ftp_user_pass = 'ftppass';
  6. $server_file = '/path_on_ftp_server/filename.ext';
  7. $local_file = '/path_to_webfolders/webdomain.com/filename.ext';
  8.  
  9. $conn_id = ftp_connect($ftp_server);
  10. $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
  11.  
  12. if ((!$conn_id) || (!$login_result)) {
  13.   echo "FTP connection has failed.\n";
  14.   echo "Attempted to connect to $ftp_server for user $ftp_user_name.\n";
  15.   exit;
  16. } else {
  17.   echo "Connected to $ftp_server.\n";
  18. }
  19.  
  20.  
  21. //UPLOAD
  22. $upload = ftp_put($conn_id, $server_file, $local_file, FTP_BINARY);
  23. if ($upload) {
  24.   echo "Uploaded $local_file to $ftp_server as $server_file.\n";
  25. } else {
  26.   echo "FTP upload has failed.\n";
  27. }
  28.  
  29. /*
  30. //DOWNLOAD
  31. $download = ftp_get($conn_id, $local_file, $server_file, FTP_BINARY);
  32. if ($download) {
  33.   echo "Successfully written to $local_file\n";
  34. } else {
  35.   echo "There was a problem\n";
  36. }
  37. */
  38. ftp_close($conn_id);
  39.  
  40. ?>

 

 

 
< Prev
Google
 
Web benconley.net
 
Top! Top!