How can PHP scripts be designed to search for the next available file name instead of overwriting existing files?

When saving files in PHP, it is important to check if the file already exists to avoid overwriting it. To search for the next available file name, you can append a suffix to the file name until a unique name is found. This can be achieved by using a loop to check if the file exists and incrementing a counter until a unique file name is found.

$filename = 'example.txt';
$counter = 1;

while (file_exists($filename)) {
    $filename = 'example_' . $counter . '.txt';
    $counter++;
}

// Now $filename contains the next available file name
// You can proceed to save the file using $filename