Rouge
Rouge

Reputation: 4239

PHP copy file issue

I am having a weird issue here

I am trying to copy file to the folder

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

My question is the $image file never gets copied to the destination

However, if I do

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

It works.

Edit:

I know the first filename statement is true.

Can anyone help me to solve this weird issue? Thanks so much!!!

Upvotes: 1

Views: 1964

Answers (3)

Jean
Jean

Reputation: 7673

It's all part of an optimization.

Since && only evaluates to true if both conditions evaluate to true, there is no point evaluating (i.e. executing)

copy($Image, $root.$imagePath)

when

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

already returned false.

As a result:

If the first copy succeeds, the second copy will not be performed because !copy(…) will have been evaluated to false.

Suggestion:

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

Upvotes: 3

Håkan
Håkan

Reputation: 186

If !copy($filename, $root.$file['dest']) evaluates to false, then there is no reason for php to try to evaluate !copy($Image, $root.$imagePath) because the entire xxx && yyy expression will be false regardless.

Upvotes: 2

Paul Roub
Paul Roub

Reputation: 36438

You probably want to say

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

(note || instead of &&)

As-is, as soon as the copy succeeds, the && will never be true, so PHP stops evaluating the expression.

In other words,

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

Upvotes: 2

Related Questions