What are some best practices for handling errors and validating file types and sizes when uploading images using PHP?

When uploading images using PHP, it is important to handle errors gracefully and validate file types and sizes to ensure security and prevent potential issues. One way to achieve this is by checking the file type and size before processing the upload. This can be done by using PHP functions like `getimagesize()` to validate the image type and `$_FILES['file']['size']` to check the file size.

// Check if file is an image
$image_info = getimagesize($_FILES['file']['tmp_name']);
if($image_info === false) {
    // Handle error - file is not an image
}

// Check if file size is within limits
$max_file_size = 2 * 1024 * 1024; // 2MB
if($_FILES['file']['size'] > $max_file_size) {
    // Handle error - file size exceeds limit
}

// Proceed with image upload
// Your image upload code here