What are the best practices for handling image uploads and resizing in PHP?

When handling image uploads in PHP, it is important to validate the file type, size, and dimensions to prevent security risks and ensure optimal performance. To resize images, you can use libraries like GD or Imagick to create thumbnails or resize the image proportionally.

// Example code for handling image uploads and resizing in PHP using GD library

// Validate file type, size, and dimensions
$allowedTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 5 * 1024 * 1024; // 5MB
$maxWidth = 800;
$maxHeight = 600;

if (in_array($_FILES['image']['type'], $allowedTypes) && $_FILES['image']['size'] <= $maxFileSize) {
    $image = $_FILES['image']['tmp_name'];
    list($width, $height) = getimagesize($image);

    if ($width <= $maxWidth && $height <= $maxHeight) {
        // Resize image using GD library
        $newWidth = 400;
        $newHeight = $height * ($newWidth / $width);
        $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

        if ($_FILES['image']['type'] == 'image/jpeg') {
            $source = imagecreatefromjpeg($image);
        } elseif ($_FILES['image']['type'] == 'image/png') {
            $source = imagecreatefrompng($image);
        }

        imagecopyresampled($resizedImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

        // Save resized image
        imagejpeg($resizedImage, 'resized_image.jpg', 80);

        imagedestroy($source);
        imagedestroy($resizedImage);
    } else {
        echo 'Image dimensions exceed the maximum allowed size.';
    }
} else {
    echo 'Invalid file type or size.';
}