CodeIgniter 2.0 new FTP class “download” method

Posted by Danny Herran on Nov 25, 2010 in Backend | 3 comments

I needed to download some files from a remote FTP server and the store them in my website. The usual way would be to download all the files to my computer and then upload them to my website. In CodeIgniter 1.7.2 you would have to do this, however, the new CodeIgniter 2.0 has a new ‘download’ method that will make it real easy to transfer files between FTP servers.

You can build a very simple controller that downloads all the files in a remote folder to our local server. Start by loading your FTP library, setting up the config information and opening the FTP session. Then get a list of the files in the directory, walk through them and download every single file in that folder.

$this->load->library('ftp');

$config['hostname'] = 'ftp.example.com';
$config['username'] = 'your-username';
$config['password'] = 'your-password';
$config['debug'] = TRUE;

$this->ftp->connect($config);

$files = $this->ftp->list_files('home/remotesite/public_html/images/');

foreach($files as $file)
{
  // $file contains the full path to the file. Only tested on Linux.
  $this->ftp->download($file, '/home/localsite/public_html/images/'.basename($file));
}

$this->ftp->close();

This is very important: make sure you use the full server paths when working with the FTP class. I made the mistake of working with the path displayed in my FTP client and found out that PHP didn’t like it. Also, don’t use relative paths.

Make sure your local folder has the correct permissions so PHP can write in that folder. In some systems you may need to CHMOD 777 your local folder, depending on your Apache configuration.

  • I’m glad you like it. I suggested this was added to the core about 4 years ago. 6 months ago it got added. 🙂

    • Phil, what a pleasure to have you around. Indeed, it was a much needed feature, finally we have it now!

  • cartalot

    Thank You!!!

    And the tip about the full path name was key.