• We just launched and are currently in beta. Join us as we build and grow the community.

Optimizing the Uploaded Image in PHP Tutorial

Legendary

Legend
L Rep
0
0
0
Rep
0
L Vouches
0
0
0
Vouches
0
Posts
58
Likes
0
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
In this tutorial, I will show you a way how to upload images in PHP with reduced quality and resized resolution. This kind of feature might be helpful to your current or future project that uploads and displays lots of images. It will help your project load the pages faster even there are a lot of images are being shown because instead of displaying the original size and quality of the images is optimized. For example, you are developing a Blog Site and each blog or article has a thumbnail or banner image. On your list page, you want to display the thumbnails or images of the articles listed. So, instead of displaying the image that has the original size and resolution, you can display the optimized images so that the list page will load faster even though lots of images are being loaded on the page.

In this article, I will show you a simple web program that contains an uploading feature and displays it. The application will also upload the original copy of the image and creates an optimized copy and save them both in different directories. I will be using a MySQL Database to store the images paths. Uploaded optimized images will be loaded on the right side of the panel with the links displaying the original and optimized images so you can compare. The source code only reduces the quality of the low-resolution images. The system will only create a resized copy of the uploaded image that is larger than 640x480 pixels resolution.

Getting Started

Download the following to your local machine:

  • The latest version of XAMPP

Install the XAMPP into your local machine. Next, open the XAMPP's php.ini

file
and uncomment GD Library extension to enable it. After that, open the XAMPP's Control Panel and start the Apache and MySQL Server.

Open your preferred browser and browse the XAMPP's PHPMyAdmin by browsing http://localhost/phpmyadmin

.

Creating the Database

Create a new database naming dummy_db. After that, navigate the page into the SQL tab of your newly created database. Then, paste the SQL Script below into the provided text field and click the Go button below to execute the SQL Script.

  1. CREATE

    TABLE

    `uploaded_

    files`

    (
  2. `id`

    int

    (

    30

    )

    NOT

    NULL

    AUTO_INCREMENT

    PRIMARY KEY

    ,
  3. `original_

    path`

    text

    NOT

    NULL

    ,
  4. `thumbnail_

    path`

    text

    NOT

    NULL


  5. )

    ENGINE

    =

    InnoDB

    DEFAULT

    CHARSET

    =

    utf8mb4;

Creating the Database Connection File

Open your preferred text editor such as notepadd++ or sublime text. Create a new PHP File naming db-connect.php. Save the file inside your source code directory's root path. Then, copy/paste the script below.


  1. <?php
  2. $host

    =

    'localhost'

    ;
  3. $username

    =

    'root'

    ;
  4. $pw

    =

    ''

    ;
  5. $dbname

    =

    'dummy_db'

    ;

  6. $conn

    =

    new

    mysqli(

    $host

    ,

    $username

    ,

    $pw

    ,

    $dbname

    )

    ;
  7. if

    (

    !

    $conn

    )

    {
  8. die

    (

    "Cannot connect to the database. Error:"

    .

    $conn

    ->

    error

    )

    ;
  9. }

Creating the Interface

Next, create a new PHP File naming index.php. This file contains the scripts of displaying the elements of the application. I contains the uploading form and display area of the uploaded images. Uploaded images will only display the optimized images.

  1. <?php require_once(

    'db-connect.php'

    )

    ; ?>
  2. <!DOCTYPE html>
  3. <html

    lang

    =

    "en"

    >
  4. <head

    >
  5. <meta

    charset

    =

    "UTF-8"

    >
  6. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  7. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  8. <title

    >

    Optimzing Uploaded Images</

    title

    >
  9. </

    head

    >
  10. <style

    >
  11. html, body{
  12. width:100%;
  13. margin:unset;
  14. }
  15. .text-center{
  16. text-align:center;
  17. }
  18. .panel-row{
  19. width:100%;
  20. display:flex;
  21. padding: 0 15px;
  22. }
  23. .left-panel{
  24. width:30%;
  25. padding: .5rem;
  26. min-height:10rem;
  27. border-radius:.5rem;
  28. }
  29. .right-panel{
  30. width:70%;
  31. padding: .5rem;
  32. display:flex;
  33. flex-wrap:wrap;
  34. }
  35. input[type="file"]{
  36. width:100%;
  37. }
  38. .img-holder{
  39. width:20%;
  40. height:15vh;
  41. padding:.5em;
  42. margin-bottom:1.8em
  43. }
  44. .img-holder>img{
  45. width:100%;
  46. height:100%;
  47. object-fit:scale-down;
  48. object-position:center;
  49. background: #000c;
  50. }
  51. @media (max-width:680px){
  52. .panel-row{
  53. flex-direction:column
  54. }
  55. .left-panel, .right-panel{
  56. width:100%;
  57. }
  58. .img-holder{
  59. width:90%;
  60. height:40vh;
  61. }
  62. }
  63. </

    style

    >
  64. <body

    >
  65. <h2

    class

    =

    "text-center"

    >

    Optimizig Uploaded Images</

    h2

    >
  66. <hr

    >
  67. <div

    class

    =

    "panel-row"

    >
  68. <div

    class

    =

    "left-panel"

    >
  69. <form

    action

    =

    "upload.php"

    method

    =

    "POST"

    enctype

    =

    "multipart/form-data"

    >
  70. <h4

    class

    =

    "text-center"

    ><b

    >

    Upload Image</

    b

    ></

    h4

    >
  71. <input

    type

    =

    "file"

    name

    =

    "img"

    accept

    =

    "image/png, image/jpeg"

    required>
  72. <small

    ><i

    >

    Accepts only PNG and JPEG Files</

    i

    ></

    small

    >
  73. <br

    >
  74. <br

    >
  75. <center

    >
  76. <button

    >

    Upload</

    button

    >
  77. </

    center

    >
  78. </

    form

    >
  79. </

    div

    >
  80. <div

    class

    =

    "right-panel"

    >
  81. <?php
  82. $query =

    $conn->

    query("SELECT * FROM `uploaded_files`");
  83. while($row = $query->fetch_assoc()):
  84. ?>
  85. <div

    class

    =

    "img-holder"

    >
  86. <img

    src

    =

    "<?= $row['thumbnail_path'] ?>

    " alt="">
  87. <br

    >
  88. <div

    class

    =

    "text-center"

    ><a

    href

    =

    "<?= $row['original_path'] ?>

    " target="_blank">Original</

    a

    ></

    div

    >
  89. <div

    class

    =

    "text-center"

    ><a

    href

    =

    "<?= $row['thumbnail_path'] ?>

    " target="_blank">Optimized</

    a

    ></

    div

    >
  90. </

    div

    >
  91. <?php endwhile; ?>
  92. </

    div

    >
  93. </

    div

    >
  94. <?php $conn->

    close(); ?>
  95. </

    body

    >
  96. </

    html

    >

Creating the Upload Script

Lastly, create a new PHP File naming upload.php. This is where the main scripts for our goal on this tutorial be found. The below PHP Script contains the uploading the original and optimized copies of the image. This contains also the code of saving the paths of the images in the database.

  1. <?php
  2. require_once

    (

    'db-connect.php'

    )

    ;
  3. if

    (

    $_SERVER

    [

    'REQUEST_METHOD'

    ]

    ==

    'POST'

    )

    {
  4. if

    (

    isset

    (

    $_FILES

    [

    'img'

    ]

    )

    &&

    !

    empty

    (

    $_FILES

    [

    'img'

    ]

    [

    'tmp_name'

    ]

    )

    )

    {
  5. $img

    =

    $_FILES

    [

    'img'

    ]

    ;
  6. // Orginal uploaded images directory
  7. $original_dir

    =

    "originals/"

    ;
  8. //Creating Directory if not exists
  9. if

    (

    !

    is_dir

    (

    $original_dir

    )

    )
  10. mkdir

    (

    $original_dir

    )

    ;

  11. // uploaded images thumbnail directory
  12. $thumbnail_dir

    =

    "thumbnails/"

    ;
  13. //Creating Directory if not exists
  14. if

    (

    !

    is_dir

    (

    $thumbnail_dir

    )

    )
  15. mkdir

    (

    $thumbnail_dir

    )

    ;

  16. //FileName
  17. $fname

    =

    $img

    [

    'name'

    ]

    ;

  18. // Checking Duplicate Filename
  19. $i

    =

    0

    ;
  20. while

    (

    true

    )

    {
  21. if

    (

    $i

    ==

    0

    )

    {
  22. if

    (

    !

    is_file

    (

    $original_dir

    .

    $fname

    )

    &&

    !

    is_file

    (

    $thumbnail_dir

    .

    $fname

    )

    )

    {
  23. break

    ;
  24. }
  25. }

    else

    {
  26. if

    (

    !

    is_file

    (

    $original_dir

    .

    $i

    .

    "_"

    .

    $fname

    )

    &&

    !

    is_file

    (

    $thumbnail_dir

    .

    $i

    .

    "_"

    .

    $fname

    )

    )

    {
  27. $fname

    =

    $i

    .

    "_"

    .

    $fname

    ;
  28. break

    ;
  29. }
  30. }
  31. $i

    ++;
  32. }
  33. // Image File Type
  34. $file_type

    =

    mime_content_type

    (

    $img

    [

    'tmp_name'

    ]

    )

    ;
  35. $oupload

    =

    false

    ;
  36. $thumb_upload

    =

    false

    ;

  37. if

    (

    $file_type

    ==

    'image/png'

    )

    {
  38. // For PNG Files
  39. $gdimg

    =

    imagecreatefrompng

    (

    $img

    [

    'tmp_name'

    ]

    )

    ;
  40. if

    (

    $gdimg

    )

    {
  41. $oupload

    =

    imagepng

    (

    $gdimg

    ,

    $original_dir

    .

    $fname

    ,

    9

    )

    ;
  42. list

    (

    $width

    ,

    $height

    )

    =

    getimagesize

    (

    $img

    [

    'tmp_name'

    ]

    )

    ;
  43. if

    (

    $width

    >

    640

    ||

    $height

    >

    480

    )

    {
  44. if

    (

    $width

    >

    $height

    )

    {
  45. $perc

    =

    (

    $width

    -

    640

    )

    /

    $width

    ;
  46. $width

    =

    640

    ;
  47. $height

    =

    $height

    -

    (

    $height

    *

    $perc

    )

    ;
  48. }

    else

    {
  49. $perc

    =

    (

    $height

    -

    480

    )

    /

    $height

    ;
  50. $height

    =

    480

    ;
  51. $width

    =

    $width

    -

    (

    $width

    *

    $perc

    )

    ;
  52. }
  53. }
  54. $gdimg

    =

    imagescale(

    $gdimg

    ,

    $width

    ,

    $height

    )

    ;
  55. $thumb_upload

    =

    imagepng

    (

    $gdimg

    ,

    $thumbnail_dir

    .

    $fname

    ,

    6

    )

    ;
  56. imagedestroy

    (

    $gdimg

    )

    ;
  57. }

    else

    {
  58. echo

    '<script>alert("Invalid PNG File.")</script>'

    ;
  59. }
  60. }

    else

    if

    (

    $file_type

    ==

    'image/jpeg'

    )

    {
  61. // For JPEG Files
  62. $gdimg

    =

    imagecreatefromjpeg

    (

    $img

    [

    'tmp_name'

    ]

    )

    ;
  63. if

    (

    $gdimg

    )

    {
  64. $oupload

    =

    imagejpeg

    (

    $gdimg

    ,

    $original_dir

    .

    $fname

    ,

    100

    )

    ;
  65. list

    (

    $width

    ,

    $height

    )

    =

    getimagesize

    (

    $img

    [

    'tmp_name'

    ]

    )

    ;
  66. if

    (

    $width

    >

    640

    ||

    $height

    >

    480

    )

    {
  67. if

    (

    $width

    >

    $height

    )

    {
  68. $perc

    =

    (

    $width

    -

    640

    )

    /

    $width

    ;
  69. $width

    =

    640

    ;
  70. $height

    =

    $height

    -

    (

    $height

    *

    $perc

    )

    ;
  71. }

    else

    {
  72. $perc

    =

    (

    $height

    -

    480

    )

    /

    $height

    ;
  73. $height

    =

    480

    ;
  74. $width

    =

    $width

    -

    (

    $width

    *

    $perc

    )

    ;
  75. }
  76. }
  77. $gdimg

    =

    imagescale(

    $gdimg

    ,

    $width

    ,

    $height

    )

    ;
  78. $thumb_upload

    =

    imagejpeg

    (

    $gdimg

    ,

    $thumbnail_dir

    .

    $fname

    ,

    50

    )

    ;
  79. imagedestroy

    (

    $gdimg

    )

    ;
  80. }

    else

    {
  81. echo

    '<script>alert("Invalid JPEG File.")</script>'

    ;
  82. }
  83. }

    else

    {
  84. echo

    '<script>alert("Invalid Image type.")</script>'

    ;
  85. }
  86. if

    (

    $oupload

    &&

    $thumb_upload

    )

    {
  87. $sql

    =

    "INSERT INTO `uploaded_files` (`original_path`, `thumbnail_path`) VALUES ('{$original_dir}

    {$fname}

    ', '{$thumbnail_dir}

    {$fname}

    ') "

    ;
  88. $save

    =

    $conn

    ->

    query

    (

    $sql

    )

    ;
  89. if

    (

    $save

    )

    {
  90. echo

    '<script>alert("Image has been uploaded successfully.")</script>'

    ;
  91. }

    else

    {
  92. if

    (

    is_file

    (

    $original_dir

    .

    $fname

    )

    )
  93. unlink

    (

    $original_dir

    .

    $fname

    )

    ;
  94. if

    (

    is_file

    (

    $thumbnail_dir

    .

    $fname

    )

    )
  95. unlink

    (

    $thumbnail_dir

    .

    $fname

    )

    ;
  96. echo

    'Uploading Image Failed <br>'

    ;
  97. echo

    'Error: '

    .

    $conn

    ->

    error

    ;
  98. exit

    ;
  99. }
  100. }

    else

    {
  101. echo

    'Uploading Image Failed <br>'

    ;
  102. exit

    ;
  103. }

  104. }

    else

    {
  105. echo

    '<script>alert("No Image file has been sent.")</script>'

    ;
  106. }
  107. }

    else

    {
  108. echo

    '<script>alert("No Data has been sent.")</script>'

    ;
  109. }

  110. $conn

    ->

    close

    (

    )

    ;
  111. echo

    '<script>location.replace("./")</script>'

    ;
  112. ?>

That's it! You can now check the application and see if it works as we planned and if it achieves our goal of this tutorial. You can test the application by browsing http://localhost/source_code_directory_name/

in to your preferred browser.

DEMO VIDEO

That's the end of this tutorial. If there's an error occurred on your end, please review your changes to your codes and try to differentiate them from the source code I provided above. You can also download the working source code I created for this tutorial. The download button is located below this article.

I hope this tutorial will help you with what you are looking for and you'll find this useful for your future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,341

323,350

Top