PHP › File Upload Handling

How should uploaded file names be sanitized and randomized to avoid security risks and naming conflicts when storing files on the server?

Intermediate

Answer

Uploaded file names, since they originate from user input, should never be trusted or used directly as the final storage file name without sanitization, since a malicious file name could contain path traversal sequences or unexpected characters, and a common best practice is to generate a completely new, randomized file name, such as a unique identifier combined with the original file extension, both eliminating naming conflicts between different users' uploads and removing any risk associated with the original, untrusted file name.
$extension = pathinfo($_FILES['document']['name'], PATHINFO_EXTENSION);
$safeFileName = bin2hex(random_bytes(16)) . '.' . $extension;
move_uploaded_file($_FILES['document']['tmp_name'], 'uploads/' . $safeFileName);
Real-world example A document management system generates a completely random file name for every uploaded file, storing the original user provided file name separately in a database record for display purposes, while the actual file on disk uses a safe, randomly generated name.

Common follow-ups: Why is it risky to use the original uploaded file name directly as the storage file name?;How do you keep track of the original file name if the storage file name is randomized?