цикл while с оператором ++, считающий только один раз

Я принял код от https://stackoverflow.com/a/44553006/8719001

но не могу понять, почему при загрузке одного и того же файла «test.jpg» несколько раз он учитывается только один раз, создавая «test-1.jpg», но не более, т.е. test-2.jpg, test-3.jpg.

Кто-нибудь может определить проблему и помочь, пожалуйста?

 $keepFilesSeperator = "-";
$keepFilesNumberStart = 1;

if (isset($_FILES['upload'])) {
// Be careful about all the data that it's sent!!!
// Check that the user is authenticated, that the file isn't too big,
// that it matches the kind of allowed resources...
$name = $_FILES['upload']['name'];
//If overwriteFiles is true, files will be overwritten automatically.
if(!$overwriteFiles)
{
$ext = ".".pathinfo($name, PATHINFO_EXTENSION);
// Check if file exists, if it does loop through numbers until it doesn't.
// reassign name at the end, if it does exist.
if(file_exists($basePath.$name))
{
$operator = $keepFilesNumberStart;

//loop until file does not exist, every loop changes the operator to a different value.
while(file_exists($basePath.$name.$keepFilesSeperator.$operator))
{
$operator++;
}
$name = rtrim($name, $ext).$keepFilesSeperator.$operator.$ext;
}
}
move_uploaded_file($_FILES["upload"]["tmp_name"], $basePath . $name);
}

0

Решение

Ваше условие цикла while имеет проблему

while( file_exists( $basePath.$name.$keepFilesSeperator.$operator ) )

имя $ переменная по-прежнему содержит полное имя файла, в этом случае test.jpg, вы тестируете значение как /home/test.jpg-1 так что, наконец, цикл while никогда не выполняется как файл test.jpg-1 никогда не существует, поэтому вы всегда получаете Тест-1.jpg на диске, а не …-2.jpg или же …-3.jpg

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector