Reputation: 634
I have a php script at /Users/John/Site/Code/pdfsync.php
In the script I have, I am connecting to an FTP, and downloading the files recursively, however it is creating folders and download files at /Users/John/Site/, but I can't seem to figure out how to have the files downloaded at a specific location. Let's say I when I run the script, I want it to create a PDF folder, so all the files are downloaded at /Users/John/Site/Code/PDF/, not sure how to achieve this.
$ftp_server = 'test.fr';
$ftp_user_name = 'test';
$ftp_user_pass = 'test';
$server = 'test.fr';
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if ((!$conn_id) || (!$login_result))
die("FTP Connection Failed");
ftp_sync (".");
echo "Done";
ftp_close($conn_id);
function ftp_sync ($dir) {
global $conn_id;
if ($dir != ".") {
if (ftp_chdir($conn_id, $dir) == false) {
echo ("Change Dir Failed: $dir<BR>\r\n");
return;
}
if (!(is_dir($dir)))
mkdir($dir);
chdir ($dir);
}
$contents = ftp_nlist($conn_id, ".");
foreach ($contents as $file) {
if ($file == '.' || $file == '..')
continue;
if (@ftp_chdir($conn_id, $file)) {
ftp_chdir ($conn_id, "..");
ftp_sync ($file);
}
else
ftp_get($conn_id, $file, $file, FTP_BINARY);
}
ftp_chdir ($conn_id, "..");
chdir ("..");
}
Upvotes: 1
Views: 370
Reputation: 330
You can do this very easily by using this library :
The code :
$connection = new FtpConnection('host', 'username', 'password');
$client = new FtpClient($connection);
if (asyncDownload('Users/John/Site/Code/PDF', '.')) {
echo 'Done!';
}
function syncDownload($localDir, $remoteDir)
{
global $client;
if (!is_dir($localDir)) {
mkdir($localDir);
}
/**
* listDirectoryDetails method will recursively gets all the files with
* their details within the giving directory.
*/
$files = $client->listDirectoryDetails($dir, true);
foreach($files as $file) {
$client->download($file['path'], $localDir . '/' . $file['name'], true, FtpWrapper::BINARY);
}
return true;
}
Upvotes: 1
Reputation: 202088
The way your code works, the easiest solution is to change the current local working directory to the target path, before calling ftp_sync
:
chdir("/Users/John/Site/Code/PDF/");
ftp_sync (".");
Upvotes: 0