Skip to content
shama edited this page May 9, 2012 · 11 revisions

Usage

All the examples here assume you are connected. Refer to the How To Setup page for instructions on setting up a connection. Using full paths is always recommended.

Use In Controller

class YoursController extends AppController {
	public $uses = array('Ftp.Ftp');
}

Use Anywhere

App::uses('Ftp', 'Ftp.Model');
$Ftp = new Ftp();
$connected = $Ftp->connect(array(
	'host' => 'example.com',
	'username' => 'test',
	'password' => '1234',
));

List

Return a list of files from a given folder:

try {
	$files = $this->Ftp->find('all', array('conditions' => array('path' => '/path/to/remote/folder/')));
} catch (Exception $e) {
	debug($e->getMessage());
}

Upload

Upload a file to the remote server.

try {
	if ($this->Ftp->save(array(
		'local' => '/path/to/local/file',
		'remote' => '/path/to/remote/file',
	))) {
		echo 'Success!';
	}	
} catch (Exception $e) {
	debug($e->getMessage());
}

Download

Download a remote file to local server.

try {
	if ($this->Ftp->save(array(
		'local' => '/path/to/local/file',
		'remote' => '/path/to/remote/file',
		'direction' => 'down',
	))) {
		echo 'Success!';
	}
} catch (Exception $e) {
	debug($e->getMessage());
}

Delete

try {
	if ($this->Ftp->delete('/path/to/remote/file')) {
		echo 'File was deleted!';
	}
} catch (Exception $e) {
	debug($e->getMessage());
}

Error Handling

It is advised to put try/catch statements around any code that uses this plugin as shown in the examples above.

Extend Model

If you are looking to modify the model without having to modify the cakeftp plugin (that is bad unless you are contributing!) do:

App::uses('Ftp', 'Ftp.Model');
class YourThing extends Ftp {
	function beforeSave() {
		// Do something before upload/download
		return true;
	}
}

Override the FTP Found Results

Every server is different. Included in this plugin is a method that attempts to parse the file listing results the best that it can. Although its not perfect. If you would like to override this plugin method and write your own file listing parser you can do so:

App::uses('Ftp', 'Ftp.Model');
class MyFtp extends Ftp {
	public function parseFtpResults($raw = array(), $path = null, $config = array()) {
		// Parse $raw
		$out = array();
		foreach ($raw as $val) {
			$filename = trim(strrchr($val, ' '));
			$out[] = array(
				'path'		=> '/testpath',
				'filename'	=> $filename,
				'is_dir'	=> 0,
				'is_link'	=> 0,
				'size'		=> 0,
				'chmod'		=> '0644',
				'mtime'		=> 0,
				'raw'		=> $val,
			);
		}
		/**
		 * Could even parse based on config type or systype
		 * if ($config['type'] == 'ssh') { ... }
		 * if ($config['systype'] == 'UNIX') { ... }
		 */
		return $out;
	}
}

More Examples

Take a look at the Controller/ClientController.php or the Test Cases for more examples.