How can PHP be used to resize images during upload to reduce file sizes?

When uploading images, it's important to resize them to reduce file sizes and optimize loading times on websites. This can be achieved using PHP by utilizing libraries like GD or Imagick to resize the image during the upload process. By specifying the desired dimensions and quality, the uploaded image can be resized and saved in a more optimized format.

// Check if an image file is selected for upload
if(isset($_FILES['image'])){
    $file = $_FILES['image'];
    
    // Specify the desired dimensions for the resized image
    $newWidth = 500;
    $newHeight = 500;
    
    // Create a new image from the uploaded file
    $image = imagecreatefromstring(file_get_contents($file['tmp_name']));
    
    // Resize the image to the specified dimensions
    $resizedImage = imagescale($image, $newWidth, $newHeight);
    
    // Save the resized image with reduced file size
    imagejpeg($resizedImage, 'uploads/resized_image.jpg', 80);
    
    // Free up memory
    imagedestroy($image);
    imagedestroy($resizedImage);
}