Rename files in a directory using names already defined through PHP

0

I need to rename more than a thousand .bmp files located in a "screen" directory.

Files to be renamed follow this logic "2017-08-06 19-29-58.bmp", "2017-08-06 19-29-59.bmp", "2017-08-06 19-30 -00.bmp "... according to your creation data.

I already have a name for each of these files, but the new names do not follow a sequence, for example: the file "2017-08-06 19-29-58.bmp" will now be called "White Set. bmp ", the following file" 2017-08-06 19-29-59.bmp "will be renamed to" Black Set.bmp ", the next file" 2017-08-06 19-30-00.bmp "will be renamed "Red Set.bmp", and so on.

I do not know how to specify through PHP code so that the web page checks all files listed in the "screen" directory and renames them according to my list of already defined names (array).

    
asked by anonymous 07.08.2017 / 00:34

1 answer

1

If you have predefined names for the source and destination you can use a keyed array for the old name and value for the new name, and rename it using the rename function.

Example:

$caminhoBase = "/algumaPasta/"; //ou usar ./ para a pasta onde corre este arquivo php

//A chave é o nome antigo e o valor é o novo
$renomeacoes = Array(
"2017-08-06 19-29-58.bmp" => "Conjunto Branco.bmp",
"2017-08-06 19-29-59.bmp" => "Conjunto Preto.bmp",
"2017-08-06 19-30-00.bmp" => "Conjunto Vermelho.bmp");

//para cada elemento do array fazer a renomeação
foreach($renomeacoes as $antigo => $novo){
    rename("$caminhoBase$antigo","$caminhoBase$novo");
}

If instead you only have the list of new names to assign and you want to rename based on the order of the files you will already need to get the list of files with readdir check the extension and rename one by one based on the array :

$caminhoBase = "./";  //diretorio de leitura dos arquivos

//agora só os novos
$novosNomes = Array(
    "Conjunto Branco.bmp",
    "Conjunto Preto.bmp",
    "Conjunto Vermelho.bmp");

if ($handle = opendir($caminhoBase)) { //abrir o diretorio
    $i = 0;

    while (false !== ($arquivo = readdir($handle))) { //percorrer os arquivos do diretorio

        if (strpos($arquivo, ".bmp")){ //ver se é .bmp
            rename ($caminhoBase . $arquivo, $caminhoBase . $novosNomes[$i++]);
            if ($i >= count($novosNomes)){ //se já esgotou os nomes do array sai do while
                break;
            }
        }
    }
}
    
07.08.2017 / 01:04