Skip to content

Instantly share code, notes, and snippets.

@pixelsnob
Created July 13, 2012 02:14
Show Gist options
  • Save pixelsnob/3102294 to your computer and use it in GitHub Desktop.
Save pixelsnob/3102294 to your computer and use it in GitHub Desktop.
Script that recursively reads a directory, then copies the files to another (flat) directory and renames them to a unique filename
<?php
/**
* Script that recursively reads a directory, then copies the files to another
* directory. Filenames will be 20120525-1.jpg, 20120525-2.jpg, etc.
*
*/
ini_set('date.timezone', 'America/Los_Angeles');
$dir = '/Users/luis/Pictures/Nikon Transfer 2/';
$dest_dir = '/Users/luis/Pictures/raw2/';
$it = new RecursiveDirectoryIterator($dir);
$files = array();
$dates = array();
$extensions = array();
// Create separate arrays, for sorting
foreach (new RecursiveIteratorIterator($it) as $file) {
// No hidden files
if (strpos($file->getBasename(), '.') === 0) {
continue;
}
$files[] = $file->getRealPath();
$dates[] = date('Ymd', $file->getCTime());
$extensions[] = $file->getExtension();
}
array_multisort($dates, $files, $extensions);
$i = $c = 0;
$last_date = null;
foreach ($files as $file) {
$temp_date = $dates[$i];
if ($last_date == $temp_date) {
$c++;
} else {
$c = 1;
}
$last_date = $temp_date;
$filename = "{$dates[$i]}-$c.{$extensions[$i]}";
echo $file . ' ' . $dates[$i] . ' ' . $filename . "\n";
copy($file, $dest_dir . $filename);
$i++;
}
echo "$i files copied\n";
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment