PHP Script for Deleting Orphaned Images

The title for this sucks. But that is because it isn’t easy to concisely describe (in a title fashion) what the script does. Imagine you have a lot of pictures from a photo shoot in both tif and jpg formats. You pick out the jpgs you want to keep and delete the rest. You still have all the tifs and want to delete the ones without a corresponding jpg. This script will do that. It takes three arguments: directory to delete from, directory to base that on, and an optional backup directory to move instead of deleting.

If you want it to handle different extensions, edit the code where it says jpg and tif


< ?php $deleteFromDir = rtrim($argv[1], '/'); $basedOnDir = rtrim($argv[2], '/'); $backupDir = rtrim($argv[3], '/'); if(!empty($backupDir) && !file_exists($backupDir)){ if(!mkdir($backupDir)){ dir("Unable to create backup directory. Quitting\n"); } } $dh = opendir($deleteFromDir); if($dh){ while(false !== ($file = readdir($dh))){ if($file[0] != '.' && !empty($file)){ $info = pathinfo($deleteFromDir . '/' . $file); if($info['extension'] == 'tif' && !file_exists($basedOnDir . '/'. $info['filename'] . '.jpg')){ echo $file . "\n"; if(!empty($backupDir)){ rename($deleteFromDir . '/' . $file, $backupDir . '/' . $file); }else{ unlink($deleteFromDir . '/' . $file); } } } } }else{ echo "Unable to open $dir\n"; } [/sourcecode]