Gerard-Meier

Simple archiving script.

Jun 10th, 2011
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.68 KB | None | 0 0
  1. <?php
  2. set_time_limit(0);
  3.  
  4.  
  5. print "Parsing command line arguments: " . PHP_EOL;
  6. $commando   = getArgument("-exec=");//'echo "' . mt_rand() . '"';
  7. $timestamp  = time();
  8. $path       = getArgument("-outdir=");
  9. $prefix     = getArgument("-prefix=");
  10. $limit      = getArgument("-limit=");
  11. $exec       = $commando . " > " . $path . DIRECTORY_SEPARATOR . $prefix . $timestamp;
  12.  
  13. if($path == NULL || $commando == NULL || $prefix == NULL || $limit == NULL) {
  14.     exit(printUsage());
  15. }
  16.  
  17. $files = glob($path . DIRECTORY_SEPARATOR . $prefix . "*");
  18.  
  19. print PHP_EOL . PHP_EOL . "Found " . count($files) . " file(s) in " . $path . '. ';
  20.  
  21. if(count($files) > $limit) {
  22.     print "This is more than " . $limit . ", proceeding to delete files: " . PHP_EOL;
  23.  
  24.     $i = 0;
  25.     foreach($files as $file) {
  26.         if(count($files) - $i++ > $limit) {
  27.             print "\tDeleted: " . $file . PHP_EOL;
  28.  
  29.             `rm $file`;
  30.         }
  31.     }
  32.  
  33. } else {
  34.     print "This is less than the limit. No need to archive old files." . PHP_EOL;
  35. }
  36.  
  37. print PHP_EOL . PHP_EOL . "Proceeding to execute the following command: " . PHP_EOL. "\t`" . $exec . "`" . PHP_EOL;
  38.  
  39. system($exec);
  40.  
  41. print PHP_EOL . "All done, have nice day. " . PHP_EOL;
  42.  
  43. function getArgument($prefix) {
  44. global $argv;
  45.     foreach($argv as $arg) {
  46.         if(substr($arg, 0, strlen($prefix)) == $prefix) {
  47.             print "\tFound argument: " . $arg . PHP_EOL;
  48.             return substr($arg, strlen($prefix));
  49.         }
  50.     }
  51.    
  52.     return NULL;
  53. }
  54.  
  55. function printUsage() {
  56.     print "You missed one or more arguments. Example usage: " . PHP_EOL;
  57.     print "g_archiver.php -exec=echo\ 123 ";
  58.     print "-outdir=/home/user/ ";
  59.     print "-prefix=foobar. ";
  60.     print "-limit=10" . PHP_EOL . PHP_EOL;
  61.    
  62. }
  63.  
  64. // /user/sbin/logwatch --detail High
  65. ?>
Advertisement
Add Comment
Please, Sign In to add comment