简体   繁体   中英

How can I rename all files in sub-directories with prefix of sub-directory name and then move files to new directory?

I basically have a setup like this:

C:\Upload\A
C:\Upload\B
C:\Upload\C
C:\Upload\D
C:\Upload\E

Where A, B, C, D, E are always different (product IDs) and will always be a different amount (it won't always be 5 sub-directories). Each of these sub-directories contains 24 images numbered numerically 01-24.

I need to create a PHP file that runs remotely through the web (IIS) that looks at the Upload directory, gets the name of each sub-directory and appends that name to beginning of each image file contained within that sub-directory.

So, C:\\Upload\\A\\01.jpg would become C:\\Upload\\A\\A-O1.jpg as well as the other 23 images in each sub-directory.

The PHP file needs to do the same for every sub-directory within the Upload directory.

Then, once the rename is complete, the PHP needs to copy all of the directories (and their images) from the Upload directory to a different directory. Once copied, the Upload directory needs to be cleared out.

This should work:

<?php
    define('START_DIR', '/opt/lampp/htdocs/start');
    define('DEST_DIR', '/opt/lampp/htdocs/dest');
    define('SEPARATOR', '\\');

    function firstStage() {
        $d = dir(START_DIR);
        while (false !== ($entry = $d->read())) {
            if($entry != '.' && $entry != '..')
                secondStage($entry);
        }
        $d->close();
    }

    function secondStage($prefix) {
        $d = dir(START_DIR . SEPARATOR . $prefix);
        while (false !== ($entry = $d->read())) {
            if($entry != '.' && $entry != '..')
                rename(START_DIR . SEPARATOR . $prefix . SEPARATOR . $entry, DEST_DIR . SEPARATOR . $prefix . '-' . $entry);
        }
        $d->close();
    }

    firstStage();
?>

Simply call firstStage() to start the process. Make sure you have read/write access to START_DIR and DEST_DIR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM