Skip to content

Instantly share code, notes, and snippets.

@dinamic
Last active May 23, 2018 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinamic/25c1ff8ea554322783f2d5eb5aef0059 to your computer and use it in GitHub Desktop.
Save dinamic/25c1ff8ea554322783f2d5eb5aef0059 to your computer and use it in GitHub Desktop.
PHP script that would guess the type of a file using its metadata and would rename it. Often times this is caused by unsafe removal of USB media off the USB slot.
<?php
$folder = __DIR__ .'/FOUND.000';
$dir = new DirectoryIterator($folder);
$map = array(
'application/vnd.ms-excel' => 'xls',
'application/msword' => 'doc',
'application/zip' => 'zip',
'image/jpeg' => 'jpg',
// 'audio/mpeg' => 'mpeg',
);
foreach ($dir as $fileinfo) {
printf('Processing %s:', $fileinfo->getFilename());
if ($fileinfo->isDot()) {
printf(" IGNORED\n");
continue;
}
if ($fileinfo->getExtension() !== 'CHK') {
printf(" IGNORED\n\n");
continue;
}
printf(" OK\n");
$mimeType = mime_content_type($fileinfo->getRealPath());
printf("Content-type: %s\n", $mimeType);
if (!array_key_exists($mimeType, $map)) {
printf("Extension: UNKNOWN\n\n");
continue;
}
$extension = $map[$mimeType];
$newFilename = $fileinfo->getBasename() .'.'. $extension;
printf("New file name: %s\n", $fileinfo->getPath() .'/'. $newFilename);
rename($fileinfo->getRealPath(), $fileinfo->getPath() .'/'. $newFilename);
echo "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment