What are the best practices for handling image dimensions and resizing in PHP to avoid errors like "Invalid image dimensions"?

When handling image dimensions and resizing in PHP, it is important to validate the input dimensions to avoid errors like "Invalid image dimensions." One way to do this is by checking if the dimensions are valid before attempting to resize the image. This can be done by ensuring that the width and height values are greater than zero.

// Validate image dimensions before resizing
function resizeImage($imagePath, $width, $height) {
    // Check if dimensions are valid
    if ($width > 0 && $height > 0) {
        // Resize image code here
        // Example: imagecopyresampled()
    } else {
        echo "Invalid image dimensions";
    }
}

// Usage
$imagePath = "path/to/image.jpg";
$width = 500;
$height = 300;

resizeImage($imagePath, $width, $height);