jon
jon

Reputation: 1581

How can i detect if php rename() has been successfully executed?

The php docs say that the following will return true if successful or false if it fails.

rename('test/test1/','test/test2/test1/');

How do I get the true or false? If I run the exact function and it's succesful, the folder gets moved as hoped and there is no output. If it fails, then it just prints out an error message.

How do I test if true or false so that I can tell if the rename function succeeded, without the error message?

Is this the correct way?

error_reporting(0);
if(rename('test/test1/','test/test1/test2/test1/')===true){
   print 'true';
} else{
   print 'false';
}

Upvotes: 5

Views: 5993

Answers (2)

Jon
Jon

Reputation: 437376

Checking the return value is a simple issue, done just like you suggest (or maybe you could save the return value into a variable if convenient).

However, it would be better to not change the global error level and use the error control operator @ instead:

if(@rename('test/test1/','test/test1/test2/test1/')===true) { 
    // successfuly rename
}
else {
    // failed
} 

In an advanced scenario, you might also want to understand what the error condition was if there's the possibility of taking steps to correct it. To do that, you would need the error message from the warning that rename would produce. You can use a similar technique to what I describe here to achieve that.

Upvotes: 6

Brian Driscoll
Brian Driscoll

Reputation: 19635

You would simply do this to get the return value:

$success = rename($oldValue, $newValue);

You can then do whatever you need to with the value of $success.

Upvotes: 8

Related Questions