Upload and Compress Multiple Images in PHP

Recently one of our readers asked how to upload and compress multiple images in PHP. There are certain scenarios where you need to allow users to upload multiple images. These images should be optimized. It is always a good practice to optimize the images at the time of uploading.

In this article, we study uploading multiple images and how to compress images during the upload. By compressing images, we reduce the size of the original image without losing quality.

Why Need to Reduce Image File Size?

Images play an important role in your website. Eye-catching images attract the attention of readers and they would probably spend more time on the website. But at the same time, large-size images slow down your website. They require more bandwidth which makes your website take a longer time to load. The site owners must pay attention to reducing image file size and use the image compression tool for it.

I am going to show you 2 packages to compress images – TinyPNG and artisansweb/image-optimizer package.

TinyPNG is one of the popular image compressor services on the Internet. This service allows compressing 500 images per month for free through their APIs. For more than 500 images, you need to pay for them.

If you have to optimize more than 500 images per month and don’t want to pay, then use the artisansweb/image-optimizer package. This package uses the reSmush.it service for image optimization and it’s completely free.

I would recommend trying both solutions, comparing the output, and picking the one which works best for you.

Having said that, let’s take a look at how to compress images while uploading them.

Getting Started with TinyPNG

First, you need to get an API key from TinyPNG. Click here to get your API key. You just need to enter your name and email address and you will get the email for your key.

developer key

Once you get your developer key, install a PHP library provided by TinyPNG. You should have Composer installed on your system to install the library. Open the terminal in the project root directory and run the command:

composer require tinify/tinify

How to Compress Images using TinyPNG

As mentioned in the title of this article, we are going to see how to upload and compress multiple images. For this, generate the HTML form that has file input to browse multiple images. Let’s create index.php and place the code below in it.

<form method="post" enctype="multipart/form-data">
    Upload Images: <input type="file" name="images[]" accept="image/*" multiple />
    <p><button type="submit" name="submit">Submit</button></p>
</form>

To the file input, I gave the name as images[]. This is because on the server side we need an array of files as the user is going to browse multiple images.

When the user chooses the images and hits the submit button, it will send form data to the server. On the server side, we need to write code for uploading and compressing images.

<?php
// Increase PHP execution time
set_time_limit(0);
 
require_once("vendor/autoload.php");
\Tinify\setKey("YOUR_API_KEY");
 
if (isset($_POST['submit'])) {
    $supported_images = array('image/jpg', 'image/jpeg', 'image/png', 'image/webp');
 
    if (!file_exists(getcwd(). '/uploads')) {
        mkdir(getcwd(). '/uploads', 0777);
    }
 
    foreach($_FILES['images']['name'] as $key=>$val) {  
        if (in_array($_FILES['images']['type'][$key], $supported_images)) {
            $file_name = $_FILES['images']['name'][$key];
 
            // get file extension
            $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
      
            // get filename without extension
            $filenamewithoutextension = pathinfo($file_name, PATHINFO_FILENAME);

            $filename_to_store = $filenamewithoutextension.'_'.time().'.' .$ext;
            move_uploaded_file($_FILES['images']['tmp_name'][$key], getcwd().'/uploads/'.$filename_to_store);
 
            // optimize image using TinyPNG
            try {
                $source = \Tinify\fromFile(getcwd().'/uploads/'.$filename_to_store);
                $source->toFile(getcwd().'/uploads/'.$filename_to_store);
            } catch(Exception $e) {
                echo $e->getMessage();
                exit;
            }
        }
    }
    echo "Files uploaded successfully.";
}
?>

Make sure to replace the placeholder with your actual API key. In the above code, I am generating a unique file name by appending time to it. Once an image is uploaded to the server, we send the image to the TinyPNG API for optimization. In return, you get the compressed version of the image which will replace the original image at the same location.

Compress Images using Image Optimizer Package

I have developed the Image Optimizer package. Under the hood the package uses the reSmush.it service for optimizing images. If you are looking for a free service, it’s worth trying this package. The reSmush has optimized billions of images to date. This package does not require you to provide any API key or registration. Just plug it and you are done.

To get started with the Image Optimizer package, install it using the command:

composer require artisansweb/image-optimizer

Next, the server-side code will be modified as follows.

<?php
// Increase PHP execution time
set_time_limit(0);
 
require_once("vendor/autoload.php");
 
use ArtisansWeb\Optimizer;
 
if (isset($_POST['submit'])) {
    $supported_images = array('image/jpg', 'image/jpeg', 'image/png', 'image/webp');
 
    if (!file_exists(getcwd(). '/uploads')) {
        mkdir(getcwd(). '/uploads', 0777);
    }
 
    foreach($_FILES['images']['name'] as $key=>$val) {  
        if (in_array($_FILES['images']['type'][$key], $supported_images)) {
            $file_name = $_FILES['images']['name'][$key];
 
            // get file extension
            $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    
            // get filename without extension
            $filenamewithoutextension = pathinfo($file_name, PATHINFO_FILENAME);

            $filename_to_store = $filenamewithoutextension.'_'.time().'.' .$ext;
            move_uploaded_file($_FILES['images']['tmp_name'][$key], getcwd().'/uploads/'.$filename_to_store);
 
            // optimize image
            try {
                $img = new Optimizer();
                $source = getcwd().'/uploads/'.$filename_to_store;
                $img->optimize($source);
 
            } catch(Exception $e) {
                echo $e->getMessage();
                exit;
            }
        }
    }
    echo "Files uploaded successfully.";
}
?>

Here also I am applying the same logic used for TinyPNG. The uploaded image will be sent to the resmush.it service, receive the optimized version, and replace the original image.

I hope you understand how to upload and compress multiple images in PHP. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

5 thoughts on “Upload and Compress Multiple Images in PHP

  1. Than you sir. I have got lots of ideas from your youtube videos. I have a question.
    Can we display adsense ads in the search results page for google custom search.

Leave a Reply

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