Archive for April, 2014

FTP clean-up script – PHP (delete old files on server)

2 Comments »

One of my blog user “Chris” asked for FTP clean up script, so here it is:

01//CONFIG SECTION
02//*******************************************************
03// Credentials for FTP Server
04$source_server_ip = "your_domain_or_IP"; // Server IP or domain name eg: 212.122.3.77 or ftp.domain.tld
05// Credentials for FTP account
06$ftphost = "ip_or_hostname_of_ftp"; // FTP host IP or domain name
07$ftpacct = "userid"; // FTP account
08$ftppass = "password"; // FTP password
09$logs_dir = "/"; //FTP Remote Folder
10$email_notify = 'your_email@domain.com'; // Email address for backup notification
11$backupexpireindays=21; //3 weeks expire time in days, 21 days = 7*24*60
12//END OF CONFIG SECTION
13//*******************************************************
14 
15 
16//Do not edit below this line
17$backupexpireindays=($backupexpireindays*24)*3600; //convert it to seconds, 24 hours * 60 minutes * 60 seconds
18 
19// Delete any other backup with filetime greater than expire time, before create new backup
20$conn_id = ftp_connect($ftphost);
21$login_result = ftp_login($conn_id, $ftpacct, $ftppass);
22 
23ftp_chdir($conn_id, $logs_dir);
24$files = ftp_nlist($conn_id, ".");
25foreach ($files as $filename) {
26        $fileCreationTime = ftp_mdtm($conn_id, $filename);
27        //$date = date("F j, Y, g:i a", ftp_mdtm($conn_id, $filename));
28        //print "<br>Timestamp of '$filename': $date";
29        $fileAge=time();
30        $fileAge=$fileAge-$fileCreationTime;
31        if ($fileAge > $backupexpireindays) { // Is the file older than the given time span?
32               //echo "<br>The file $filename is older than Expire time :$expiretime ...Deleting\n";
33               ftp_delete($conn_id, $filename);
34               //echo "<br>Deleted<br><br>";
35               }
36}
37 
38ftp_close($conn_id);
39  
40print "Remote FTP clean up Finish deleted files older than $backupexpireindays days";
41?>

Enjoy !