0

我采用了来自https://stackoverflow.com/a/44553006/8719001的代码

但无法弄清楚为什么当多次上传同一个文件“test.jpg”时它只计数一次,创建“test-1.jpg”但不是更多,即。测试 2.jpg,测试 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);
    }
4

1 回答 1

1

您的 while 循环条件有问题

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

$name变量仍然包含文件的全名,在本例中为test.jpg 您正在测试/home/test.jpg-1之类的值,因此最终 while 循环永远不会作为文件test.jpg-1执行永远不存在,这就是为什么你总是在磁盘上得到test-1.jpg而不是...-2.jpg...-3.jpg

于 2018-03-20T19:43:54.757 回答