How To Get Images From URL And Store Them In A Zip File

In the article, we learn how to get images from URLs and store them in a zip file.

Step 1: Make an array of your image URL.

$img_array = array(
        'https://cdn.pixabay.com/photo/2018/01/14/23/12/nature-3082832_960_720.jpg', 
        'https://cdn.pixabay.com/photo/2020/03/03/20/31/boat-4899802_960_720.jpg', 
        'https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455_960_720.jpg',
        'https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg'
);

Step 2: Use the below code for creates a zip file.

$created_zip = new ZipArchive();
$create_temporary_file = tempnam('.', '');
$created_zip->open($create_temporary_file, ZipArchive::CREATE);

Step 3: Run for each loop of the image array. now get the content image and add it in zipping by using the “addFromString” function.

foreach ($img_array as $img_file) {
        $download_img_file = file_get_contents($img_file);
        $created_zip->addFromString(basename($img_file), $download_img_file);
}
Step 4: To download the zip file from the browser use the below code.
header('Content-disposition: attachment; filename="images.zip"');
header('Content-type: application/zip');
readfile($create_temporary_file);
unlink($create_temporary_file); // unlink is remove the created zip file.
Here is the full code:
<?php
    $img_array = array(
        'https://cdn.pixabay.com/photo/2018/01/14/23/12/nature-3082832_960_720.jpg', 
        'https://cdn.pixabay.com/photo/2020/03/03/20/31/boat-4899802_960_720.jpg', 
        'https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455_960_720.jpg',
        'https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg'
    );
    $created_zip = new ZipArchive();
    $create_temporary_file = tempnam('.', '');
    $created_zip->open($create_temporary_file, ZipArchive::CREATE);
    foreach ($img_array as $img_file) {
        $download_img_file = file_get_contents($img_file);
        $created_zip->addFromString(basename($img_file), $download_img_file);
    }
    $created_zip->close();
    header('Content-disposition: attachment; filename="images.zip"');
    header('Content-type: application/zip');
    readfile($create_temporary_file);
    unlink($create_temporary_file); // unlink is remove the created zip file.
?>
Here is result
 
Thanks.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories