Automate FTP File Transfers with PHP

This is a follow up to my post Useful FTP Bash Script. In that script I posted a bash script that would connect to a remote FTP server, retrieve remote files, delete remote files and disconnect. I was able to simplify that script using PHP.

Keep in mind that this script will delete the remote file, so if that is not your intent, you will need to change it by removing lines 54 – 60.

<?php

// This script will:
// 1. connect to an ftp server in the specified directory ($destdir)
// 2. Download all files in the $destdir directory to the $localdir directory
// 3. If download was successful, delete the file from $destdir

$now = date("Y-m-d H:i:s");
$nowdate = date("Y-m-d");
$thelogfilename = "/path/to/logging/FTPLOGFILE-" . $nowdate . ".txt";

if ( !file_exists($thelogfilename)){
		touch ($thelogfilename);
	}

$thelogfile = fopen($thelogfilename,'a');

fwrite($thelogfile,"*********** " . BASENAME(__FILE__) . " START AT: " . $now . " ***********\n");

// Initialise the connection parameters  
$ftp_server = "ftp.domain.net";  
$ftp_username = "myusername";  
$ftp_password = "mypass";  


// Directory to retrieve ALL files from
$destdir = "/";

// Directory to store all files to
$localdir = "/path/to/save/documents/";

// ====== SHOULDN'T NEED TO ALTER BELOW UNLESS PROCEDURE NEEDS TO BE CHANGED ====== //
// Create an FTP connection  
$conn = ftp_connect($ftp_server);  

// Login to FTP account using username and password  
if (@ftp_login($conn, $ftp_username, $ftp_password)) {
fwrite($thelogfile,"Connected as $ftp_username@$ftp_server\n");

// Get the contents of the current directory  
// Change the second parameter if wanting a subdirectories contents  
$files = ftp_nlist($conn, $destdir);  

// Loop through $files  
foreach ($files as $file)
{

	//Download section
	if (ftp_get($conn, $localdir . BASENAME($file), $file, FTP_BINARY))
	{

		fwrite($thelogfile,$file . " downloaded correctly\n");
		
		// We can delete the server file since the ftp_get was successful
		if (ftp_delete($conn, $file)) {
		fwrite($thelogfile,$file . " deleted successful\n");

		} else {
		fwrite($thelogfile,"could not delete " . $file . "\n");
		}

	} else {
		fwrite($thelogfile,$file . "NOT downloaded correctly\n");
	}

}

} else {
	fwrite($thelogfile,"Couldn't connect as $ftp_username\n");
}

$endnow = date("Y-m-d H:i:s");
fwrite($thelogfile,"*********** " . BASENAME(__FILE__) . " END AT: " . $endnow . " *************\n\n");
fclose($thelogfile);

// close the connection
ftp_close($conn); 

?>

Leave a Reply

Your email address will not be published. Required fields are marked *