What are some best practices for handling file names in PHP to ensure security and efficiency?

When handling file names in PHP, it is important to sanitize and validate user input to prevent security vulnerabilities such as directory traversal attacks. It is also crucial to ensure file names are unique to prevent overwriting existing files and to optimize performance by avoiding special characters or excessively long file names.

// Sanitize and validate file name input
$filename = filter_var($_POST['filename'], FILTER_SANITIZE_STRING);

// Generate a unique file name
$unique_filename = uniqid() . '_' . $filename;

// Remove special characters and limit file name length
$clean_filename = preg_replace("/[^a-zA-Z0-9\_\-\.]/", "", $unique_filename);