Skip to content

Instantly share code, notes, and snippets.

@cukabeka
Created January 27, 2013 23:09
Show Gist options
  • Save cukabeka/4651190 to your computer and use it in GitHub Desktop.
Save cukabeka/4651190 to your computer and use it in GitHub Desktop.
Download files from remote FTP server via PHP, as found on http://chosencollective.com/technology/download-files-recursively-with-php
<?php
# Linear connection info for connecting to FTP
# set up basic connection
$ftp_server = "ftp.yourserver.com";
$ftp_user = "Username";
$ftp_pass = "Password";
$ftp_conn = ftp_connect($ftp_server);
$ftp_login = ftp_login($ftp_conn, $ftp_user, $ftp_pass);
ftp_pasv($ftp_conn, true);
# check connection
if ((!$ftp_conn) || (!$ftp_login)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user";
} else {
echo "Connected to $ftp_server, for user $ftp_user";
}
echo "Currently in ".ftp_pwd($ftp_conn);
if (ftp_chdir($ftp_conn, "IDX_Version_5")) {
echo "Current directory is now: " . ftp_pwd($ftp_conn) . "\n";
} else {
echo "Couldn't change directory\n";
}
# Dump the data to the screen
var_dump(ftp_rawlist($ftp_conn, '.'));
# For the actual ftp actions, I use a FTP class I wrote which you can grab below
FTP::download(APPPATH.'data/idx', '.', $ftp_conn);
ftp_close($ftp_conn);
?>
<?php
# FTP Class for performing file downloads
class FTP {
/**
* Download() performs an automatic syncing of files and folders from a remote location
* preserving folder and file names and structure
*
* @param $local_dir: The directory to put the files, must be in app path and be writeable
* @param $remote_dir: The directory to start traversing from. Use "." for root dir
*
* @return null
*/
public static function download($local_dir, $remote_dir, $ftp_conn)
{
if ($remote_dir != ".") {
if (ftp_chdir($ftp_conn, $remote_dir) == false) {
echo ("Change Dir Failed: $dir<br />\r\n");
return;
}
if (!(is_dir($dir)))
mkdir($dir);
chdir ($dir);
}
$contents = ftp_nlist($ftp_conn, ".");
foreach ($contents as $file) {
if ($file == '.' || $file == '..')
continue;
if (@ftp_chdir($ftp_conn, $file)) {
ftp_chdir ($ftp_conn, "..");
FTP::download($local_dir, $file, $ftp_conn);
}
else
ftp_get($ftp_conn, "$local_dir/$file", $file, FTP_BINARY);
}
ftp_chdir ($ftp_conn, "..");
chdir ("..");
}
}
?>
Copy link

ghost commented May 12, 2014

"$dir" it is allways undefined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment