Tuesday 17 July 2018

PHP Function to Connect via FTP with Retry Capability

PHP Function to Connect via FTP with Retry Capability


Let’s face it… If something can go wrong, it will go wrong. This is no exception for FTP connections either. Maybe the remote server is not accessible, the network is down, or the connection times out.
PHP comes with a set of useful functions to deal with common FTP operations. What I want to show you in this post however is, in conjuntion with these functions, how to improve the connection aspect and add a failsafe should a connection not be available. I find this especially effective for scripts left running as a background process.
Let’s take a look at the function:
  1. function connect_to_ftp($ftp_host$ftp_user$ftp_pass$retries)  
  2. {  
  3.     $connected = false;  
  4.     $retry = 0;  
  5.       
  6.     // Keep looping until connected or met no. of retries if $retries is not zero  
  7.     while (!$connected && ($retries==0 || ($retries>0 && $retry<$retries)))  
  8.     {  
  9.         // try connecting to host  
  10.         $ftp_conn = ftp_connect($ftp_host);  
  11.           
  12.         if ($ftp_conn)  
  13.         {  
  14.             // connection was successful. now try to login  
  15.             $ftp_login = ftp_login($ftp_conn$ftp_user$ftp_pass);  
  16.               
  17.             if ($ftp_login)  
  18.             {  
  19.                 // login was successful. let's get outta here...  
  20.                 return $ftp_conn;  
  21.             }  
  22.             else  
  23.             {  
  24.                 echo "Unable to login to ".$ftp_host." using ".$ftp_user.":".$ftp_pass."\n";  
  25.             }  
  26.         }  
  27.         else  
  28.         {  
  29.             echo "Unable to establish FTP connection to ".$ftp_host."\n";  
  30.         }  
  31.           
  32.         sleep(5); // sleep for 5 seconds before trying again  
  33.           
  34.         $retry++;  
  35.     }  
  36.       
  37.     return $ftp_conn;  
  38. }  
And an example of using the function:

  1. // initialise FTP connection details  
  2. $ftp_host = 'ftp.mysite.com';  
  3. $ftp_user = 'username';  
  4. $ftp_pass = 'password';  
  5. $retries = 0; // Number of maximum retries. Set to 0 for unlimited  
  6.   
  7. // returned is an FTP connection as a resource for use in other functions  
  8. $ftp_conn = connect_to_ftp($ftp_host$ftp_user$ftp_pass$retries);  
  9.   
  10. echo 'FTP Connection: '.$ftp_conn;  

0 comments:

Post a Comment