What are the potential security risks associated with using user input as a file name in PHP file uploads?

Using user input as a file name in PHP file uploads can lead to security risks such as directory traversal attacks, allowing users to upload malicious files with executable code, and overwriting existing files on the server. To mitigate these risks, it is important to sanitize and validate user input before using it as a file name, and to generate a unique file name to prevent overwriting existing files.

// Sanitize and validate user input for file name
$fileName = preg_replace("/[^A-Za-z0-9.]/", "", $_FILES['file']['name']);

// Generate a unique file name
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . uniqid() . '_' . $fileName;

// Move the uploaded file to the specified directory
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);