5

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';
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
jon
  • 1,429
  • 1
  • 23
  • 40

2 Answers2

8

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.

Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
6

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.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806