【问题标题】:PHP copy file issuePHP复制文件问题
【发布时间】:2013-04-26 22:14:46
【问题描述】:

我遇到了一个奇怪的问题

我正在尝试将文件复制到文件夹中

 if ($folder) {
        codes.....
    } else if (!copy($filename, $root.$file['dest']) && !copy($Image, $root.$imagePath)){
             throw new Exception('Unable to copy file');
    }

我的问题是$image 文件永远不会被复制到目的地

但是,如果我这样做了

if ($folder) {
        codes.....
    } else if (!copy($Image, $root.$imagePath)){
             throw new Exception('Unable to copy file');
    }

它有效。

编辑:

我知道第一个文件名声明是正确的。

谁能帮我解决这个奇怪的问题?非常感谢!!!

【问题讨论】:

  • 我建议使用try {} catch {}
  • “我知道第一个文件名声明是正确的” - 请参阅下面的我的回答和其他人。第二个副本没有准确地发生因为第一个副本成功了。 ||而不是 && 会解决这个问题。

标签: php copy


【解决方案1】:

这都是优化的一部分。

由于&& 仅在两个条件都为真时才评价为真,因此没有意义评价(即执行)

copy($Image, $root.$imagePath)

!copy($filename, $root.$file['dest']) 

已经返回 false。

结果:

如果第一次复制成功,则不会执行第二次复制,因为!copy(…) 将被评估为假。

建议:

// Perform the first copy
$copy1 = copy($filename, $root.$file['dest']);

// Perform the second copy (conditionally… or not)
$copy2 = false;        
if ($copy1) {
    $copy2 = copy($Image, $root.$imagePath);
}

// Throw an exception if BOTH copy operations failed
if ((!$copy1) && (!$copy2)){
    throw new Exception('Unable to copy file');
}

// OR throw an exception if one or the other failed (you choose)
if ((!$copy1) || (!$copy2)){
    throw new Exception('Unable to copy file');
}

【讨论】:

  • 感谢您的回复。但是,我知道第一个副本 ($filename) 是正确的,因为我可以看到该文件。为什么第二个复制语句没有执行?
  • @Rouge 是的,没错。如果第一个副本返回 true,则 !copy(…) 返回 false。结果,第二个副本不会发生。发生第二个副本的唯一方法是第一个失败 (!false -> true)。
【解决方案2】:

你可能想说

else if (!copy($filename, $root.$file['dest']) || !copy($Image, $root.$imagePath))

(注意|| 而不是&&

照原样,一旦复制成功,&& 将永远不会为真,因此 PHP 停止计算表达式。

换句话说,

$a = false;
$b = true;
if ($a && $b) {
  // $b doesn't matter
}

【讨论】:

    【解决方案3】:

    如果 !copy($filename, $root.$file['dest']) 计算结果为 false,则 php 没有理由尝试计算 !copy($Image, $root.$imagePath) 因为无论如何,整个 xxx && yyy 表达式都会为假。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多