What best practices should be followed when generating thumbnails in PHP to optimize performance?

When generating thumbnails in PHP, it is important to follow best practices to optimize performance. One way to do this is by using a caching mechanism to store the generated thumbnails and serving them directly from the cache if they have already been created. This can help reduce the load on the server and improve the overall performance of the application.

<?php
// Check if the thumbnail already exists in the cache
$cacheFile = 'thumbnails/' . $imageFilename . '_thumb.jpg';

if (file_exists($cacheFile)) {
    // Serve the thumbnail directly from the cache
    header('Content-Type: image/jpeg');
    readfile($cacheFile);
} else {
    // Generate the thumbnail
    $originalImage = imagecreatefromjpeg($imageFilename);
    $thumbnail = imagescale($originalImage, $width, $height);

    // Save the thumbnail to the cache
    imagejpeg($thumbnail, $cacheFile);

    // Serve the generated thumbnail
    header('Content-Type: image/jpeg');
    imagejpeg($thumbnail);

    // Clean up
    imagedestroy($originalImage);
    imagedestroy($thumbnail);
}
?>