What precautions should be taken to prevent data loss when renaming files that already exist in the directory?

When renaming files that already exist in the directory, it is important to check if the new file name already exists to prevent data loss. One way to prevent data loss is to append a unique identifier to the new file name before renaming it. This ensures that the new file name is unique and does not overwrite existing files.

$directory = "/path/to/directory/";
$oldFileName = "existing_file.txt";
$newFileName = "new_file.txt";

if (file_exists($directory . $newFileName)) {
    // Append a unique identifier to the new file name
    $newFileName = uniqid() . "_" . $newFileName;
}

rename($directory . $oldFileName, $directory . $newFileName);