What are the best practices for handling image uploads and updates in PHP to prevent overwriting existing images or incorrect updates?

When handling image uploads and updates in PHP, it is important to generate unique filenames to prevent overwriting existing images and validate the file type to ensure correct updates. One way to achieve this is by appending a timestamp or a random string to the filename before saving it.

// Handle image upload
if(isset($_FILES['image'])){
    $file_name = $_FILES['image']['name'];
    $file_tmp = $_FILES['image']['tmp_name'];
    
    $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
    $new_file_name = uniqid() . '.' . $file_ext; // Generate unique filename
    
    move_uploaded_file($file_tmp, 'uploads/' . $new_file_name);
}