What are the best practices for handling file renaming in PHP, especially in a scenario like the one described in the forum thread?

Issue: When renaming a file in PHP, it is important to check if the new filename already exists to avoid overwriting existing files. One way to handle this is by appending a unique identifier to the filename before the file extension.

// Check if the new filename already exists and append a unique identifier if necessary
$filename = 'example.txt';
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$newFilename = $filename;
$counter = 1;

while (file_exists($newFilename)) {
    $newFilename = pathinfo($filename, PATHINFO_FILENAME) . '_' . $counter . '.' . $extension;
    $counter++;
}

// Rename the file with the new filename
rename($filename, $newFilename);