So i’m trying to make a function to make a Local copy of a folder and all contents (with sub-folders) and send a copy to a remote server, the local copy is fine but the ftp copy is not formatted the way it should. They both have all of the files but the ftp version is not formatting the file structure right. I looked but can not find any post with this problem, so any pointers would be helpful.
Example: correct
- Main
- sub-1
- sub-2
- sub-3
- sub-4
- sub of 4 – 1
- sub of 4 – 2
But this is what I get,
- main
- sub 4
- sub 0f 4 – 1
- sub 0f 4 – 2
- sub 3
- sub 2
- sub 1
- sub 2
- sub 3
- sub 0f 4 – 2
- sub 0f 4 – 1
- sub 4
Here is the code:
function copyr($source, $dest, $conId) {
$sourceName = explode('/',$dest);
$sourceName = $sourceName[count($sourceName)-1];
// copy file
if (is_file($source)) {
$upLink = ftp_fput($conId, $sourceName, fopen($source, 'r'), FTP_ASCII);
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest);
ftp_mkdir($conId, $sourceName);
ftp_chdir($conId, $sourceName);
} else if(is_dir($dest)){ // go to one that has been made.
ftp_chdir($conId, $sourceName);
}
// Loop the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Copy sub directories
if ($dest !== "$source/$entry") {
copyr("$source/$entry", "$dest/$entry", $conId, $entry);
}
}
// Clean up
$dir->close();
return true;
}
$source = 'images';
$dest = 'NewImages';
if(copyr($source, $dest, $conId)){
echo "It's finished .... Good.";
} else {
echo "Failed ... ";
}
ftp_close($conId);
Part of this I copied from php.net the other parts a put together after looking at the .net Manual for ftp.
Thanks.
You forgot to back out of the directory (e.g.
cd ..) after returning from the recursion.