How can PHP developers prevent duplicate file names when uploading files?

To prevent duplicate file names when uploading files in PHP, developers can append a timestamp or a unique identifier to the file name before saving it to the server. This ensures that each file uploaded will have a distinct name and avoids overwriting existing files with the same name.

// Generate a unique file name by appending a timestamp
$timestamp = time();
$originalFileName = $_FILES['file']['name'];
$extension = pathinfo($originalFileName, PATHINFO_EXTENSION);
$newFileName = $timestamp . '_' . $originalFileName;

// Move the uploaded file to a directory with the new unique file name
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $newFileName);