Saturday, January 30, 2010

PHP for file moving / managing

PHP is a technology damned cool for web application but the language doesn't provide an advanced syntax as Python in itself. However, by writing readable and maintenable code (for instance by smartly separating features in function and classes), PHP is satisfying also to make file managing / system scripts, IMHO of course :)

Example
Here is a simple script I'm using to copy the latest mp3 files from a directory to another one (ipod shuffle) skipping the already existing files. Basically it's a kind of one-way-sync script for files filtered by mask and creation date. (To run it from the command line, launch it from the destination directory. e.g.: "php -f script.php" in the root of the ipod, or any USB MP3 player)



define('_SOURCE_PATH_', 'd:/documents/Music/incoming/');
define('_DEST_FOLDER_' , 'Music/'); #ipod shuffle

foreach (new DirectoryIterator(_SOURCE_PATH_) as $f) {

if ( Utils::is_recent_mp3( $f->getPathname() ) &&
Utils::copy_if_not_exists( $f->getPathname(), _DEST_FOLDER_.$f->getFilename() )
)
echo "[COPIED][{$f->getFilename()}]\n";

}




class Utils {

public static function is_recent_mp3($path, $daysOld = 7) {
return ( substr($path,-1)=='3' && filemtime($path) > ( time()-$daysOld*24*3600) );
}

public static function copy_if_not_exists($from, $to){
return ( file_exists($from) && !file_exists($to) ) ? copy($from, $to) : false;
}

}

No comments:

Post a Comment

 

PHP and tips|PHP