PHP复制文件问题

时间:2013-04-26 22:14:46

标签: php copy

我在这里遇到一个奇怪的问题

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

 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');
    }

有效。

修改

我知道第一个文件名是真的。

任何人都可以帮我解决这个奇怪的问题吗?非常感谢!!!

3 个答案:

答案 0 :(得分:4)

这是优化的全部内容。

由于&&仅在两个条件评估为true时才评估为true,因此无评估(即执行)

copy($Image, $root.$imagePath)

何时

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

已经返回false。

结果:

如果第一个副本成功,则不会执行第二个副本,因为!copy(…)将被评估为false。

<强>建议:

// 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');
}

答案 1 :(得分:2)

你可能想说

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

(注意||而不是&&

按原样,一旦复制成功,&&将永远不会成立,因此PHP停止评估表达式。

换句话说,

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

答案 2 :(得分:2)

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