简体   繁体   中英

Renaming a file using rename() function with counter in php

Hello gurus in the house. Please i want to rename a file using rename() function, but this will be if/while the file exist let it use counter to rename to another file.

example, if sitemap.txt exist let it rename it to sitemap1.txt if sitemap1.txt exist let it rename it to sitemap2.txt , if sitemap.txt , sitemap1.txt , sitemap2.txt exist let it rename it to sitemap3.txt and so on.

$filename = 'sitemap.txt';
$FileCounter = 1;
while (file_exists( $filename )){
rename($filename, "sitemap". $FileCounter++ .".txt");
}

the above is the piece of code it works but each time sitemap1 exist, it refuses to move over to the next counter which is sitemap2.txt

I don't really how to make the counter work fine. but I need this only on rename() function.

Thanks you in advance.

a solution could be to do the first rename, then loop until a file is reached, in order to rename it to the next counter:

    // if sitemap exists,
    if (file_exists("sitemap.txt")) {
        // rename it to sitemap1
        rename("sitemap.txt", "sitemap1.txt");
    }
    // if not, likely sitemaps1+ exist
    else {
        // init a new counter
        $FileCounter = 0;
        do {
            // increment the counter to check the next sitemap file
            $FileCounter++;
            // if sitemap<n> exists, break the loop
            $exist = file_exists("sitemap{$FileCounter}.txt");
        } while (!$exist);
        // prepare source and destination counters (n and n + 1)
        $NextFileCounter = $FileCounter + 1;
        // perform the rename
        rename("sitemap{$FileCounter}.txt", "sitemap{$NextFileCounter}.txt");
    }

this should work, let me know if current snippet is what you were looking for!

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