• Sales: 1-800-961-2888
  • Support: 1-800-961-4454

How do I remove files older than a certain date, like logs and sessions?

The UNIX find utility is disabled for performance reasons. In order to find older files and delete them, one must create a script that performs similar logic.

Below is a way to do this using a PHP script and a HTML form as a cron job alternative.




Before implementing this, you should know the following:

This is not a cron job!

This is not designed to be used as a cron job. To use as a cron job, either:

  • Hard code the arguments passed over HTML GET


  • Pass the arguments on the CLI and use argv[0] and argv[1].

Example 1

ex1 $dir = opendir("/mnt/stor1-wc1-dfw1/111111/www.testform.com/web/content/logs") or die("Could not open directory");

Example 2

ex2 $dir  = opendir($argv[0)) or die("Could not open directory");

Security -- BE SURE TO READ!

This form will allow anyone that can access it to delete your content. You'll want to secure it with a .htaccess file, and you may want to delete the form when you're done with it.

The HTML form

The HTML form that sends the directory and age to the PHP script is as follows:

         <form action="del_old.php" method="get">

             Directory: <input type="text" name="dir"><br>
             Days Old: <input type="text" name="days"><br>

             <input type="submit">

The PHP script

The PHP script that takes args from HTML GET query string can be constructed as follows:

  * DISCLAIMER: Use at your own risk. Rackspace claims no responsibility for any loss of data that occurs when using this script.
  * Pass from a HTML form the directory to be searched eg. /mnt/stor1-wc1-dfw1/111111/www.testform.com/web/content/log/
  * Pass from a HTML form the age of files to be deleted in days. eg. "10" is any files that have not been modifed in 10 days

$dir = opendir($_GET["dir"]) or die("Could not open directory");

$old = mktime(0,0,0,date("m"),date("d")-$_GET["days"],date("Y"));
echo "Working in <tt>".$_GET["dir"]."</tt><br>";
echo "Deleting files created before <tt>".date("F d Y", $old)."</tt><br><br>";

while(($dirent = readdir($dir)) != false)
         $cur = filemtime($dirent);
         if($cur < $old)
                 echo "<del><b><tt>$dirent</tt></b></del> modified <b><tt>".date("F d Y H:i:s",$cur)."</tt></b><br>";
                 echo "Error deleting file <tt><b>$dirent</b></tt><br>";
             echo "<b><tt>$dirent</tt></b> modified <b><tt>".date("F d Y H:i:s",$cur)."</tt></b><br>";


© 2011-2013 Rackspace US, Inc.

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License

See license specifics and DISCLAIMER