SFTPainless

At White Whale I maintain several libraries of code which involve performing tasks over FTP. PHP has an FTP extension that works pretty well for FTP-related code. The major flaw with it is that it only supports FTP and FTP+SSL. As we start working more and more with SFTP servers, many of these libraries needed to add SFTP support.

There is an SSH2 module that requires a little more effort to set up on your web server, but enables support for SFTP servers. The question is then, how can I integrate this extension and its features into an existing FTP codebase in an efficient manner? Furthermore, the SSH2 module’s syntax is not as straightforward for basic FTP tasks as the actual FTP extension is.

The answer is really pretty simple. I created an FTP wrapper class which runs in one of three modes: FTP, SSL, or SFTP. Depending on the mode, the wrapper class reroutes its method calls to the appropriate extension. All the methods for this class exactly match the ones for the FTP extension. In the case of FTP and SSL, it is easy to map the methods from one to the other, because they’re exactly the same. In the case of SFTP, there’s a translation layer which converts FTP commands in the FTP extension’s syntax to the SSH2 extension’s equivalents.

The reason this approach is efficient is because all the existing code can be painlessly converted to the wrapper class, such that SFTP is instantly supported. No alternate SFTP code paths, no significant code rewrites, no new syntax to follow. What it boils down to is one extra step to specify the FTP mode, and then just prefixing each FTP function call with the wrapper object (i.e. ftp_put to $ftp->ftp_put). Done!

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One responses to “SFTPainless”:

  1. areapeas says:

    i would use the ssh2 extension if it worked on shared hosts, but alas, it does not. atleast not on most i’ve seen. you can use this in its stead:

    http://phpseclib.sourceforge.net/

    has a pure-php sftp implementation.

Add your response: