PHP Function to Connect via FTP with Retry Capability

February 21st, 2012 - Posted by Steve Marks to PHP, Web Development.

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:

function connect_to_ftp($ftp_host, $ftp_user, $ftp_pass, $retries)
{
	$connected = false;
	$retry = 0;
	
	// Keep looping until connected or met no. of retries if $retries is not zero
	while (!$connected && ($retries==0 || ($retries>0 && $retry<$retries)))
	{
		// try connecting to host
		$ftp_conn = ftp_connect($ftp_host);
		
		if ($ftp_conn)
		{
			// connection was successful. now try to login
			$ftp_login = ftp_login($ftp_conn, $ftp_user, $ftp_pass);
			
			if ($ftp_login)
			{
				// login was successful. let's get outta here...
				return $ftp_conn;
			}
			else
			{
				echo "Unable to login to ".$ftp_host." using ".$ftp_user.":".$ftp_pass."\n";
			}
		}
		else
		{
			echo "Unable to establish FTP connection to ".$ftp_host."\n";
		}
		
		sleep(5); // sleep for 5 seconds before trying again
		
		$retry++;
	}
	
	return $ftp_conn;
}

And an example of using the function:

// initialise FTP connection details
$ftp_host = 'ftp.mysite.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$retries = 0; // Number of maximum retries. Set to 0 for unlimited

// returned is an FTP connection as a resource for use in other functions
$ftp_conn = connect_to_ftp($ftp_host, $ftp_user, $ftp_pass, $retries);

echo 'FTP Connection: '.$ftp_conn;
Tags: , ,
This entry was posted on Tuesday, February 21st, 2012 at 10:23 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first