What is the best practice for resizing images in PHP when displaying them on a webpage?

When displaying images on a webpage, it's important to resize them appropriately to improve loading times and ensure they fit the layout. One common approach is to use PHP to resize images on the server-side before serving them to the client. This can be achieved using the GD library in PHP, which provides functions for image manipulation such as resizing.

// Load the image
$source = imagecreatefromjpeg('image.jpg');

// Get the dimensions of the original image
$sourceWidth = imagesx($source);
$sourceHeight = imagesy($source);

// Calculate the desired width and height for the resized image
$targetWidth = 300; // Set the desired width
$targetHeight = ($targetWidth / $sourceWidth) * $sourceHeight;

// Create a new image with the desired dimensions
$target = imagecreatetruecolor($targetWidth, $targetHeight);

// Resize the image
imagecopyresampled($target, $source, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);

// Output the resized image
header('Content-Type: image/jpeg');
imagejpeg($target);

// Clean up
imagedestroy($source);
imagedestroy($target);