You can give this a try
define("FILE_COPY", 1);
define("FILE_MOVE", 2);
$dirSource = __DIR__ . "/case";
$dirDestination = $dirSource . "/books";
$cache = $errors = array();
$allowDuplicate = false;
$mode = FILE_COPY; // copy or move file ;
try {
$dirIT = new FilesystemIterator($dirSource, FilesystemIterator::SKIP_DOTS);
$regexIT = new RegexIterator($dirIT, '/.pdf$/i');
// Make Directory
if (! is_dir($dirDestination) and ! @mkdir($dirDestination, 0777, true)) {
throw new Exception("Destination Folder ($dirDestination) does not exist");
}
foreach($regexIT as $splFile) {
$hash = md5_file($splFile);
$ext = "." . $splFile->getExtension();
// Don't take duplicates
if (! $allowDuplicate && isset($cache[$hash])) {
continue;
}
// Split File Name
list($category, $name, $subCategory) = explode("_", $splFile->getBasename($ext));
if (empty($category) || empty($name) || empty($subCategory)) {
$errors[] = "File ($splFile) does not have valid name format";
}
// New File path
$path = sprintf("%s/%s/%s", $dirDestination, $category, $subCategory);
if (! is_dir($path) and ! @mkdir($dirDestination, 0777, true)) {
throw new Exception("Destination Folder ($path) does not exist");
}
$fileTmp = $path . DIRECTORY_SEPARATOR . $splFile->getFileName();
if (is_file($fileTmp)) {
if (! $allowDuplicate) {
// Check if file is duplicate
$copyhash = md5_file($fileTmp);
if ($hash == $copyhash) {
continue;
}
}
$x = 1;
while(is_file($fileTmp)) {
$fileTmp = $path . DIRECTORY_SEPARATOR . $splFile->getBasename($ext) . "_" . $x . $ext;
$x ++;
}
}
if ($mode == FILE_COPY) {
if (! copy($splFile, $fileTmp))
$errors[] = "File ($splFile) Failed Copy";
} else {
if (! rename($splFile, $fileTmp))
$errors[] = "File ($splFile) Failed Move";
}
$cache[$hash] = true;
}
} catch (Exception $e) {
echo $e->getMessage();
}