What are best practices for handling file uploads in PHP to avoid creating duplicate files?

To avoid creating duplicate files when handling file uploads in PHP, it is best practice to generate a unique filename for each uploaded file. This can be achieved by appending a timestamp or a random string to the original filename before saving it to the server.

// Get the original filename
$originalFilename = $_FILES['file']['name'];

// Generate a unique filename
$uniqueFilename = uniqid() . '_' . $originalFilename;

// Move the uploaded file to a specific directory with the unique filename
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $uniqueFilename);