How can PHP be used to optimize and resize images uploaded by users to ensure optimal performance on a website?

When users upload images to a website, it's important to optimize and resize them to ensure optimal performance. This can be achieved using PHP by checking the file type, resizing the image if necessary, and saving the optimized version. This will help reduce load times and improve overall site performance.

// Check if the uploaded file is an image
if(isset($_FILES['image']['tmp_name']) && getimagesize($_FILES['image']['tmp_name'])) {
    $image = $_FILES['image']['tmp_name'];
    
    // Resize the image
    $new_width = 300; // Set the desired width
    list($width, $height) = getimagesize($image);
    $new_height = ($height/$width) * $new_width;
    
    $new_image = imagecreatetruecolor($new_width, $new_height);
    $old_image = imagecreatefromjpeg($image);
    
    imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    
    // Save the optimized image
    imagejpeg($new_image, 'optimized_image.jpg', 80); // Save the image with 80% quality
}