How can PHP developers optimize the process of temporarily storing and validating externally linked images before displaying them on a webpage?

When displaying externally linked images on a webpage, PHP developers can optimize the process by temporarily storing the images locally on the server, validating them to ensure they are safe to display, and then serving them from the local storage to improve performance and security.

<?php
// Function to store and validate externally linked images
function storeAndValidateImage($url) {
    $image = file_get_contents($url);
    $imagePath = 'images/'.basename($url);
    
    // Validate image file type
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    $imageType = getimagesizefromstring($image)['mime'];
    
    if (!in_array($imageType, $allowedTypes)) {
        return false;
    }
    
    // Save image locally
    file_put_contents($imagePath, $image);
    
    return $imagePath;
}

// Example usage
$imageUrl = 'https://example.com/image.jpg';
$localImagePath = storeAndValidateImage($imageUrl);

if ($localImagePath) {
    echo '<img src="'.$localImagePath.'" alt="External Image">';
} else {
    echo 'Invalid image type';
}
?>