What are the best practices for handling file uploads in PHP to avoid conflicts with existing data or uploads?

When handling file uploads in PHP, it is important to avoid conflicts with existing data or uploads by implementing proper file naming conventions and checking for file existence before overwriting. One common approach is to append a timestamp or unique identifier to the file name to ensure uniqueness.

// Check if file already exists, if so, append a timestamp
$uploadDir = 'uploads/';
$fileName = $_FILES['file']['name'];
$filePath = $uploadDir . $fileName;

if (file_exists($filePath)) {
    $timestamp = time();
    $fileName = $timestamp . '_' . $fileName;
    $filePath = $uploadDir . $fileName;
}

// Move uploaded file to designated directory
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);

echo 'File uploaded successfully!';