How can PHP be used to ensure that each new file created has a unique name based on user input?

When creating new files based on user input, it is important to ensure that each file has a unique name to prevent overwriting existing files. One way to achieve this is by appending a timestamp or a random string to the user input to create a unique file name. This can be done using PHP functions like time() or uniqid().

$user_input = "example"; // User input for file name
$unique_filename = $user_input . "_" . uniqid(); // Concatenate user input with unique identifier
$file_path = "path/to/directory/" . $unique_filename . ".txt"; // Define the file path with the unique filename

// Create the new file with the unique name
$file = fopen($file_path, "w");
fclose($file);