note 53291 deleted from function.rename by cmb
| From: | cmb@php.net | Date: | Sun, 22 Dec 2019 09:12:28 +0000 |
| Subject: | note 53291 deleted from function.rename by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213602@lists.php.net to get a copy of this message | ||
Note Submitter: JRog
----
To anyone wondering, rename($old, $new) returns FALSE if $new already exists. My script called for
overwriting the file if it existed so I did this:
if(file_exists($new)) { unlink($new); }
$ok = rename($old, $new);
This did not work as expected. If $new actually existed then it worked fine. That is the file
found at path $new was deleted and replaced with the file found at path $old. However, if $new did
NOT exist then the result was the file at path $old vanished into oblivion. After debugging a bit,
it seems that rename() was getting executed before the if-statement. So rename() moved $old to
$new, THEN the if-statement evaluated to true and deleted the file I just moved. Anyway, this fixed
it:
if(file_exists($new)) {
unlink($new);
$ok = rename($old, $new);
} else { $ok = rename($old, $new); }
Very strange ... I hope this helps somebody