2013-04-26 47 views
1

我有在這裏一個奇怪的問題PHP複製文件的問題

我試圖文件複製到該文件夾​​

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

它的工作原理。

編輯:

我所知道的第一個文件名說法是正確的。

任何人都可以幫助我解決這個奇怪的問題嗎?非常感謝!!!

+0

我建議使用'try {} catch {}' – 2013-04-26 22:19:53

+0

「我知道第一個文件名語句是真實的」 - 請參閱下面的我的答案和其他內容。第二個副本沒有精確地發生*,因爲*第一個副本成功。 ||而不是&會解決這個問題。 – 2013-04-26 22:34:02

回答

3

這是優化的一部分。

由於&&只計算結果爲真,如果兩個條件評價爲真,沒有一點評價(即執行)

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

感謝您的回覆。但是,我知道第一個副本($ filename)是真的,因爲我可以看到該文件。爲什麼第二個複製語句沒有執行? – Rouge 2013-04-26 22:31:30

+0

@Rouge確實如此。如果第一個副本返回true,那麼'!copy(...)'返回false。因此,第二個副本不會發生。第二個副本發生的唯一方法是首先失敗(!false - > true)。 – Jean 2013-04-26 22:32:12

+0

感謝您的解釋。我現在明白了。 – Rouge 2013-04-26 22:35:41

2

你可能想說

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

(注意||代替&&

原來的樣子,只要複製成功, &&永遠不會成立,所以PHP停止評估表達式。

換句話說,

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

謝謝+1 ........ :) – Rouge 2013-04-26 22:36:08

2

如果!副本($文件名,$根。$文件[ 'DEST'])計算爲false,那麼沒有理由爲PHP,試圖評估!複製($ Image,$ root。$ imagePath),因爲整個xxx & & yyy表達式將不管。

+0

謝謝+1 ..... :) – Rouge 2013-04-26 22:34:48