What best practices should be followed when generating file names dynamically based on existing files in PHP?

When generating file names dynamically based on existing files in PHP, it is important to ensure that the new file name is unique to avoid overwriting existing files. One common approach is to append a timestamp or a unique identifier to the file name. Additionally, it is a good practice to sanitize the file name to remove any special characters that could cause issues.

// Example code snippet for generating a unique file name based on existing files
$existingFiles = ['file1.txt', 'file2.txt', 'file3.txt'];

$newFileName = 'newfile.txt';
$counter = 1;
while (in_array($newFileName, $existingFiles)) {
    $newFileName = 'newfile' . $counter . '.txt';
    $counter++;
}

// Sanitize the file name to remove special characters
$newFileName = preg_replace('/[^a-zA-Z0-9_.]/', '', $newFileName);

echo $newFileName; // Output: newfile4.txt