Products Drag & Drop Objects Drag & Drop Calendar Drag & Drop Form Code View
Order
Testimonials Downloads
dynamicreport.com News Members Forum Knowledge Base Site Map
Support Support Ticket Contact Us

Knowledge Base Print printer-friendly page.

Login
ddobj
Forum
News


Article #1013: Delete, Search and Modify Files Recursively Using PHP

 

The following snippet of code provides basic functionality to process files beginning with the root directory and traversing through subsequent files and folders. The parameters to function dirtree($root, $callback, $params) include: the starting or root directory, a custom callback function that applies a process on each file, and a parameter that will be used by the pre-defined callback function. The callback parameter may be a scalar value or an array of values. In the example below it will be an associative array containing a single element for the purpose of simplicity, as is apparent of the callback function definition.

function dirtree ($root, $callback, $params)
{
 if (!is_dir ($root.DIRECTORY_SEPARATOR))
  return false; // root directory doesn't exist
 $d = dir ($root.DIRECTORY_SEPARATOR);
 while (false !== ($entry = $d->read ()))
 {
  $path = $root.DIRECTORY_SEPARATOR.$entry;
  if (is_dir ($path) && $entry != "." && $entry != "..")
   dirtree ($path, $callback, $params);
  else if (is_file ($path))
   $callback ($path, $params);
 }
 $d->close ();
}

Code View - dynamicreport.com

The callback function receives the path to the file (includes the filename), and the parameter originally passed to function dirtree(...), which is propagated to the callback function. The callback function is defined to delete all files on or before a specific date contained in the parameter.

function delfile ($fn, $params)
{
 $ft = strtotime (date ("m/d/Y", filemtime ($fn)));
 // delete files on or before the date parameter
 if ($ft <= $params['date'])
  unlink ($fn);
}

Code View - dynamicreport.com

In application -- the call to function dirtree(...) will be passed the parameters described above. Following the parameters of root folder and callback function is the callback parameter itself, which in this case contains a date that will be used by the callback function delfile(...) defined above. The callback parameter itself could have been specified as just the date value, but instead an array was used so as to provide a template for passing multiple parameters to the custom callback function.

dirtree ("mydir".DIRECTORY_SEPARATOR."filesdir", delfile, array ("date" => strtotime ("09/20/2007")));

Code View - dynamicreport.com

 
 

Back to article listing

 


 

Copyright © 2007-2008 Interaxis. All rights reserved.
Contact Webmaster