How can one efficiently handle and save multiple images from external URLs in a loop using PHP?

When handling and saving multiple images from external URLs in a loop using PHP, it is important to use proper error handling and validation to ensure that the images are downloaded correctly and saved successfully. One efficient way to achieve this is by using the file_get_contents() function to fetch the image data from the external URL and then saving it to a local file using file_put_contents().

<?php

// Array of image URLs
$imageUrls = [
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg',
    'https://example.com/image3.jpg'
];

// Loop through each image URL
foreach ($imageUrls as $imageUrl) {
    // Get the image data from the URL
    $imageData = file_get_contents($imageUrl);

    // Save the image data to a local file
    $localImagePath = 'images/' . basename($imageUrl);
    file_put_contents($localImagePath, $imageData);

    // Check if the image was saved successfully
    if (file_exists($localImagePath)) {
        echo "Image saved successfully: $localImagePath" . PHP_EOL;
    } else {
        echo "Error saving image: $imageUrl" . PHP_EOL;
    }
}

?>