Copying FTP files via PHP

set_time_limit(0); $ftp_server = "server"; $ftp_user = "user"; $ftp_pass = "pass"; // set up a connection or die $ftp_conn = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server"); ftp_set_option($ftp_conn, FTP_TIMEOUT_SEC, 18000); // try to login $ftp_login = ftp_login($ftp_conn, $ftp_user, $ftp_pass); // check connection if ((!$ftp_conn) || (!$ftp_login)) { die("FTP connection has failed !"); } else { print_r("we are connected as ". $ftp_user . "<br>"); } // set connection to passive ftp_pasv( $ftp_conn, true ); // get the child directory ftp_chdir($ftp_conn, 'image'); // get contents of the current directory $contents = ftp_nlist($ftp_conn, "."); // loop through all the contents as a file, and move them to a new location. foreach ($contents as $file) { $local_file = $_SERVER['DOCUMENT_ROOT']. '/ftp_copy/' . trim($file, './'); if(!file_exists($local_file)) { $server_file = $file; if (ftp_get($ftp_conn, $local_file, $server_file, FTP_BINARY)) { echo "Successfully written to $local_file\n"; } else { echo "There was a problem\n"; } } } // close the connection ftp_close($ftp_conn);
I required a method for copying over files from one server to another via a Cron job, and need a script to do this. Core PHP allows you to do this pretty neatly, however it was a tiny bit annoying to set up. Here is the code I used.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.