What are some best practices for error handling in PHP scripts, specifically when dealing with image processing functions like imagecreatefrom and getimagesize?

When dealing with image processing functions in PHP, it is important to handle errors gracefully to prevent potential security vulnerabilities and unexpected behavior. One best practice is to use try-catch blocks to catch exceptions and handle errors appropriately. Additionally, checking the return values of functions like imagecreatefrom and getimagesize can help detect errors early on.

try {
    $image = @imagecreatefromjpeg('image.jpg');
    if (!$image) {
        throw new Exception('Failed to create image from file');
    }

    $imageSize = @getimagesize('image.jpg');
    if ($imageSize === false) {
        throw new Exception('Failed to get image size');
    }

    // Proceed with image processing
} catch (Exception $e) {
    // Handle the error, log it, or display a user-friendly message
    echo 'An error occurred: ' . $e->getMessage();
}