Search code examples
phpforeachgloborganizationfile-management

Copy Files from folders to folder tree in php


I have a large number of books that I need to categorize by language and libraryID.

The file-names are structured like this and spread out in many folders:

ENG_FILENAME_LIBRARYNAME1.pdf
ENG_FILENAME_LIBRARYNAME2.pdf
SPA_FILENAME_LIBRARYNAME1.pdf
SPA_FILENAME_LIBRARYNAME2.pdf

I need to move them into folders like this

ENG
->LIBRARYNAME1
--ENG_FILENAME_LIBRARYNAME1.pdf
->LIBRARYNAME2
--ENG_FILENAME_LIBRARYNAME2.pdf

Here's my code:

foreach (glob("C:/wamp/www/projects/filemove/eth/*") as $folderpath) {
$foldername = preg_replace('/.*?\/(.*?)/', '$1', $folderpath);
    foreach (glob("C:/wamp/www/projects/filemove/eth/*/*") as $librarypath) {
    $libraryname = preg_replace('/.*?\/(.*?)/', '$1', $librarypath);

        foreach (glob("C:/wamp/www/projects/filemove/pdf/*.pdf") as $filepath) {
           $ethologue = preg_replace('/(.*?)_.*/', '$1', $filepath);
           $library = preg_replace('/.*?_.*?_.*?_(.*?)_.*/', '$1', $filepath);
           $filename = preg_replace('/.*?\/(.*?)/', '$1', $filepath);

           if ($ethologue = $foldername ) {
           if ($library = $libraryname) {
                copy($filepath, $librarypath);
                }
           }
        }
    }
}

Thanks in advance!


Solution

  • 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();
    }