Skip to content

Instantly share code, notes, and snippets.

@WintersMichael
Created August 21, 2012 22:17
Show Gist options
  • Save WintersMichael/3419917 to your computer and use it in GitHub Desktop.
Save WintersMichael/3419917 to your computer and use it in GitHub Desktop.
QnD php cli ftp spy
<?php
//Super Q&D. Monitors a single FTP directory for new files.
//Modify the vars below and run as 'php ftpmon.php'.
//Notification is via growlnotify, which requires purchase of growl.
$host = "ftp.host.com";
$user = "ftpuser";
$pass = "secret";
$dir = "/somedir/";
$sleeptime = 60;
date_default_timezone_set('America/Chicago');
function notify($title, $message) {
system("growlnotify -t '$title' -m '$message' -s");
}
//---------------------------------------
set_time_limit(0); //infinite
$mtime = '';
$mdate = '';
$mmonth = '';
$mname = '';
$found = false;
while (!$found) {
$conn = ftp_connect($host) or die("Couldn't connect\n");
ftp_login($conn, $user, $pass) or die("Couldn't log in\n");
$contents = ftp_rawlist($conn, "-lt $dir");
sizeof($contents) or die("Couldn't get file listing\n");
ftp_close($conn);
$file = explode(' ', $contents[0]); //most-recent file. Looks like this:
/*
array(15) {
[0]=>
string(10) "-rwxr--r--"
[1]=>
string(0) ""
[2]=>
string(0) ""
[3]=>
string(1) "1"
[4]=>
string(7) "user"
[5]=>
string(0) ""
[6]=>
string(7) "group"
[7]=>
string(0) ""
[8]=>
string(10) "2785658880"
[9]=>
string(3) "Aug"
[10]=>
string(2) "17"
[11]=>
string(5) "09:36"
//12 is the filename. Anything above 12 is because the filename has spaces in it.
[12]=>
string(6) "pics-2"
[13]=>
string(1) "-"
[14]=>
string(13) "condo-old.tar"
}
*/
//var_dump($file);
if (strlen($mtime) == 0) {
//init
$mtime = $file[11];
$mdate = $file[10];
$mmonth = $file[9];
$mname = $file[12]; //XXX Should grab everything 12+ in case of spaced filenames but this is just for UI
echo "First run. Most recent file is '$mname' at $mmonth $mdate $mtime\n";
sleep($sleeptime);
continue;
}
if ($file[11] != $mtime) {
$found = true;
echo date(DATE_ATOM) . " - notifying & exiting.\n";
notify('FTP site updated', $contents[0]);
} else {
echo date(DATE_ATOM) . " - Not found, sleeping $sleeptime.\n";
sleep($sleeptime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment