Last active
May 23, 2018 11:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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