Why is it recommended to validate and generate file names separately when using "file_put_contents" in PHP?

When using file_put_contents in PHP, it is recommended to validate and generate file names separately to prevent security vulnerabilities such as directory traversal attacks. By validating the file name separately, you can ensure that it only contains allowed characters and does not allow for malicious input. Generating the file name separately also helps to avoid conflicts with existing files and ensures that the file is saved in the correct location.

$filename = "example.txt";
$validated_filename = preg_replace('/[^a-zA-Z0-9\_\-\.]/', '', $filename);
$file_contents = "Hello, world!";
file_put_contents($validated_filename, $file_contents);