Wednesday, April 08, 2009

How to upload same file to 2 different Servers.

This could be done in 2 simple Steps:

1. First upload to the main server or the one where the php scripts are hosted.

2. Second, either via a cron job running after a specific time or in the upload script itself copy the files to the other server.

The below sample code is to copy the file to second server using FTP functions.

// Details of the second server.
$host = 'host';
$user = 'username';
$pass = 'password';

//Path of the uploaded file i.e. on first server.
$local_file = 'path of file/file.txt' ;

//Path of the second file.
$remote_file = 'path of file/file.txt' ;

// set up basic connection
$conn_id = ftp_connect($host);

// login with username and password
$login_result = ftp_login($conn_id, $user, $pass);

// check connection
if ((!$conn_id) || (!$login_result)) {

echo "Cannot initiate connection to host";
exit;
}
else {

// upload the file
$upload = ftp_put($conn_id, $remote_file, $local_file, FTP_BINARY);

//Close FTP connection
ftp_close($conn_id);
}

No comments: