PHP - 更新前的备份文件

I created a function to get the latest version of some file from github and update the local one. Here is the code:

$remoteFile = $remote; // File from github.
$localFile = $local; // File to be updated (/app/lib/example.php).

// If file exists, it must be copied to a backup (.bak) version.
if (file_exists($localFile)) {
    rename($localFile, $localFile.'.bak');
}

$newFile = fopen($localFile, 'w');
fwrite($newFile, file_get_contents($remoteFile));
fclose($newFile);

The problem is that this code updates the file before renaming it. In other words, the current and the backup files will have the same updated code. Anybody knows why?