Home php How to Optimize Image On Upload In PHP ?

How to Optimize Image On Upload In PHP ?

by Shahriar Sagor

Today now in this post i will show you how to optimize images on upload in PHP. Some days ago, I was decided to write an article on that how we can reduce or compress any file size at the time of uploading it. Here we will know how to optimize image on upload in php.

We know as a developer file uploading is our regular basis task. We are always do it in a traditional way. By Using the the built-in function move_uploaded_file we can move the images to the directory and then leave them as it is. If do we think on a few points as like what is the size of the uploaded image? Here we know this image take time to load on a website? So we can optimize an image without losing its quality?

We know that images is play an important role in the site speed. By using heavy images it can slow down the page speed which in result loses your audiences and also traffic. So in this situation is not affordable. Here we are take a lot of effort to build the audience and traffic. So as a good practice is, we should optimize the image while uploading.

So in this article, I am going to use TinyPNG  service for optimizing any images. I will also write a code for it in moments.

Use TinyPNG to Optimize Image On Upload

To get the started we need to install the TinyPNG library. For Install the library we can using the command below.

composer require tinify/tinify

After the installing the library, we get our API key from TinyPNG website.

Note: TinyPNG allows compressing only 500 images free per month. For more than 500 images we have to pay them. If we are running a small website then i hope his quota is enough.

Once we are ready with the API key, then let’s start with code. I am creating a simple HTML form that contains file input and a submit button.

<form method="post" enctype="multipart/form-data">
    <p><input type="file" name="myfile" accept="image/*" required /></p>
    <button type="submit" name="submit">Submit</button>
</form>

When any users upload an image using this form, developers need to write the below kind of code to move the uploaded image on the server.

if (isset($_POST['submit'])) {
 
    $allowed_mime_types = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
 
    if (!in_array($_FILES['myfile']['type'], $allowed_mime_types)) {
        echo 'Invalid file format.';
        exit();
    }
 
    if (!file_exists(getcwd().'/uploads')) {
        mkdir(getcwd().'/uploads', 0777);
    }
 
    $src_file_name = $_FILES['myfile']['name'];
    move_uploaded_file($_FILES['myfile']['tmp_name'], getcwd().'/uploads/'.$src_file_name);
 
    echo "File uploaded successfully";
}

Now the above code is correct and there is no issue in it except the missing part of the optimization of the image. For the optimizing images, we just need to add 2 lines more of code after the move_uploaded_file statement.

$source = \Tinify\fromFile(getcwd().'/uploads/'.$src_file_name);
$source->toFile(getcwd().'/uploads/'.$src_file_name);
Our final code is as follows.
<?php
require_once("vendor/autoload.php");
 
\Tinify\setKey("TINYPNG_API_KEY"); //pass your actual API key
 
if (isset($_POST['submit'])) {
 
    $allowed_mime_types = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
 
    if (!in_array($_FILES['myfile']['type'], $allowed_mime_types)) {
        echo 'Invalid file format.';
        exit();
    }
 
    if (!file_exists(getcwd().'/uploads')) {
        mkdir(getcwd().'/uploads', 0777);
    }
 
    $src_file_name = $_FILES['myfile']['name'];
    move_uploaded_file($_FILES['myfile']['tmp_name'], getcwd().'/uploads/'.$src_file_name);
 
    //optimize image using TinyPNG
    $source = \Tinify\fromFile(getcwd().'/uploads/'.$src_file_name);
    $source->toFile(getcwd().'/uploads/'.$src_file_name);
 
    echo "File uploaded successfully.";
}
?>
<form method="post" enctype="multipart/form-data">
    <p><input type="file" name="myfile" accept="image/*" required /></p>
    <button type="submit" name="submit">Submit</button>
</form>

I hope you are understand how to optimize the image on upload in PHP.

Read Also: How To Implement Laravel 9 form validation ?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like