Building a FTP client library with PHP


In my daily work I need to connect very often to FTP servers. Put files, read, list and things like that. I normally use the standard PHP functions for Ftp it’s pretty straight forward to use them. Just enable it within our installation (–enable-ftp) and it’s ready to use them. But last Sunday it was raining again and I start with this simple library.

Lets connect to a FTP server, switch to passive mode, put a file from one real file stored in our local filesystem and delete it.

use FtpLib\Ftp,
    FtpLib\File;

list($host, $user, $pass) = include __DIR__ . "/credentials.php";

$ftp = new Ftp($host, $user, $pass);
$ftp->connect();
$ftp->setPasv();

$file = $ftp->putFileFromPath(__DIR__ . '/fixtures/foo');
echo $file->getName();
echo $file->getContent();
$file->delete();

Now the same, but without a real file. We are going to create the file on-the-fly from one string:

use FtpLib\Ftp,
    FtpLib\File;

list($host, $user, $pass) = include __DIR__ . "/credentials.php";

$ftp = new Ftp($host, $user, $pass);
$ftp->connect();
$ftp->setPasv();

$file = $ftp->putFileFromString('bar', 'bla, bla, bla');
echo $file->getName();
echo $file->getContent();
$file->delete();

We also can create directories, change the working directory and delete folders in the FTP server with a fluent interface (I love fluent interfaces, indeed):

$ftp->mkdir('directory')
  ->chdir('directory')
  ->putFileFromString('newFile', 'bla, bla')
  ->delete();

$ftp->rmdir('directory');

And finally we can iterate files in the FTP (I must admit that this feature was the main purpose of the library)

$ftp->getFiles(function (File $file) use ($ftp) {
    switch($file->getName()) {
        case 'file1':
            $file->delete();
            break;
        case 'file2':
            $ftp->mkdir('backup')->chdir('backup')->putFileFromString($file->getName(), $file->getContent());
            break;
    }
});

And that’s all. You can find the library in github and you also can use it with composer.

"gonzalo123/ftplib": "dev-master"

You can also see usage examples within the unit tests

About these ads

About Gonzalo Ayuso

Web Architect specialized in Open Source technologies. PHP, Python, JQuery, Dojo, PostgreSQL, CouchDB and node.js but always learning.

Posted on November 12, 2012, in php, PHPUnit, Technology and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 953 other followers

%d bloggers like this: