簡體   English   中英

使用operator ++進行while循環僅計數一次

[英]while loop with operator++ only counting up once

我通過了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);
    }

您的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的原因

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM