Can you use PHP to copy Folder from one host to another?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Can you use PHP to copy Folder from one host to another?

Post by simonmlewis »

Code: Select all

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// 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);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>
This works for copying a file from one host to another.
But is there a similar fairly simple script, that copies an entire folder, from one to another?
I didn't write this, so I am not sure if this can be modified easily to do such a thing?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Can you use PHP to copy Folder from one host to another?

Post by requinix »

Define "fairly simple".

Code: Select all

function ftp_put_recursive($conn_id, $remote_path, $path) {
	if $path is a directory {
		for each $thing in $path {
			// assuming $thing is the full path, not just a name
			ftp_put_recursive($conn_id, $remote_path . "/" . basename($thing), $thing);
		}
	} else if $path is a file {
		ftp_put($conn_id, $remote_path, $path);
	} // else $path doesn't exist so don't do anything
}
User avatar
Tiancris
Forum Commoner
Posts: 39
Joined: Sun Jan 08, 2012 9:54 pm
Location: Mar del Plata, Argentina

Re: Can you use PHP to copy Folder from one host to another?

Post by Tiancris »

In a web application I'm working on, we have a cron executing a php script. This cron is running as root user and the script is out of public access, so we have enough privileges to copy files from a web site to another doing the following:

Code: Select all

$from = '/home/site1/source_dir/.';
$to = '/home/site2/destination_dir/';
exec("cp -R $from $to");
Nice, isnt it? :)
Post Reply