【问题标题】:while loop with operator++ only counting up once带有 operator++ 的 while 循环只计数一次
【发布时间】:2018-03-20 19:21:51
【问题描述】:

我采用了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);
    }

【问题讨论】:

  • 你不将每个文件的变量 $operator 重新定义为 1 吗?我的意思是,你可以只上传 1 个文件还是 2 个文件(test-1.jpg 和 test-2.jpg)?
  • file_exists($basePath.$name.$keepFilesSeperator.$operator) 应该是 file_exists($basePath.rtrim($name, $ext).$keepFilesSeperator.$operator.$ext),因为这是您将它们移动到的地方。
  • @I-V 运算符从 1 开始,并在 while 循环中以 ++ 向上计数。逻辑检查适用于每个单独的上传。
  • @JonStirling 感谢您发布实际代码,这很有效!我怀疑它没有被触发但不知道为什么,因为我在循环之后有 rtrim 但意识到它仍然需要它来实际写出新文件名:)。

标签: php while-loop operator-keyword character-trimming


【解决方案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

【讨论】:

  • 感谢 Jonnathan 指出问题,我怀疑它从未被触发,但没有意识到我也需要循环中的 rtrim。乔恩将上面的代码发布在有效的 cmets 中:)
猜你喜欢
  • 2015-09-28
  • 1970-01-01
  • 2016-08-21
  • 2015-03-23
  • 2011-11-02
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多