简体   繁体   中英

PHP rename and concatenation adds extra numbers

I have the following code which operates as follows: option 1 renames the files in a folder with a random string option 2 renames the files in an incremental manner. The issue is for some reason the loop runs twice, leaving me with numbers starting from greater than 0. Can anybody notice anything wrong with the logic?

if ($handle = opendir('../images/IL')) {
    $nameCount = 0;
    while (false !== ($fileName = readdir($handle))) {
        $nameCount++;
        //opt 1 for random, opt 2 numeric incremental naming

        $opt = 2;

        if( inString('.jpg', $fileName) == 'true') {
            if($opt == 1) {
            $newName = '';
            $newName = genword( 8, 5 );
            rename('../images/IL/'.$fileName, '../images/IL/'.$newName.'.jpg');
        } 
        else if ( $opt == 2 ) {
            rename('../images/IL/'.$fileName, '../images/IL/image '.$nameCount.'.jpg');             
        }
    }
closedir($handle);
}

You do

$nameCount = 0;

before the loop and at the beginning of the loop

$nameCount++;

at the beginning of the loop. Therefore, the files lowest number is 1.

$nameCount is being incremented on every iteration of the while loop. This means that $nameCount is incremented for files with names that do not contain ".jpg", eg blah.gif and this includes directories of which there are always 2: . the current directory, and .. the parent directory.

So, given that $nameCount is immediately incremented, it's effective initial value is 1. Then add 2 for the current and parent directories. Plus any other files or directories that do not contain the substring .jpg - and that is why you find that the renamed files do not have the expected sequence.

Poor indentation, particularly the $opt if/else handling, might have contributed to this misunderstanding. Try this instead:

<?php
$img_dir = '../images/IL/';

function inString($needle, $haystack)
{
    if (strstr($haystack, $needle) != FALSE)
        return 'true';
    return 'false';
}

if ($handle = opendir($img_dir)) {
    $nameCount = 0;
    while (false !== ($fileName = readdir($handle))) {
        //opt 1 for random, opt 2 numeric incremental naming
        $opt = 2;

        if (inString('.jpg', $fileName) == 'true') {
            if ($opt == 1) {
                $newName = '';
                $newName = genword( 8, 5 );
                rename($img_dir.$fileName, $img_dir.$newName.'.jpg');
            }
            else if ($opt == 2) {
                $nameCount++;
                rename($img_dir.$fileName, $img_dir.$nameCount.'.jpg');
            }
        }
    }

    closedir($handle);
}

Note that $nameCount is now incremented only when a file is renamed.

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