How to upload multiple images and create image gallery in PHP

An image gallery gives a list of images displayed as thumbnails. You can dynamically create an image gallery by uploading images along with the caption for each image using PHP and MySQL. Use JavaScript and jQuery to preview images before upload and also delete images after upload using Ajax.

In this topic, we will develop an application in PHP and MySQL using which you can upload multiple images with the caption for each image and create an image gallery using the uploaded images.

image gallery in phpAssumption

  1. You must have basic knowledge of HTML, CSS, JavaScript and jQuery.
  2. You must know how Ajax works (Ajax is used here only to delete an image, not to upload image). You can read below topics for more details:
    1. How to install xampp for Windows with setup for PHP development
    2. How to write PHP code with examples for beginners
    3. How to build a simple CRUD application in PHP and MySQL

image gallery in phpFolders and Files

Below is a screenshot of the folder structure and files I am using:

multiple files upload in PHP and MySQL

I have created a folder named 'image_gallery' under 'xampp/htdocs' as I am using XAMPP. If you are using WAMP, create 'image_gallery' folder under 'www'.

  1. Folder 'cfg' - In this folder I have kept dbconnect.php which is used to connect to the MySQL database.
  2. Folder 'css' - Custom stylesheet is in this folder
  3. Folder 'js' - In this folder contains custom JavaScripts file
  4. Folder 'uploads' - All uploaded images will be stored in this folder
  5. gallery.php - Displays image gallery for all uploaded images
  6. index.php is the screen where user can upload, view and delete photos
  7. modal.php/code> is for displaing images in modal
  8. process_image.php is the PHP program that uploads, deletes, displays photos

Below is the screenshot of the upload page when 8 images were uploaded and the image gallery is given after that:

Upload Image Page

Upload multiple photos PHP home page

Image Gallery Page

Image Gallery in php

Upload images section can be treated as an Admin activity, Admin can manage the images. Image gallery can be viewed in your website.

Step 1 - Create a MySQL table to store image files

Let us create a table named 'images' in MySQL database. I have a database called 'demo'. So, this table will be created in demo database. If you have an existing database other than demo you can also use it. Just make sure same table do not exist already. Table structure and create table scripts are given below:

Table: images

This table stores image captions and image file names of all uploaded images

image gallery in php

Table has 4 columns.

  1. id - Unique id of each image, it is the primary key and auto incremented
  2. image_name - Image name entered by the user while uploading
  3. image_file - File name of uploaded image
  4. upload_dt - Date on which image was uploaded, default current timestamp
Create table script for this table is given below, you can use this code to create the table. Also, if you download code (see in download section) you will get all the scripts.

images.sql

After you create the table, please verify if structure is same as above.

Step 2 - Connect to MySQL database (dbconnect.php)

Use below script to connect to the database. Note that we have this database connection php program in 'cfg' folder. This is written once and used in every program where database connection is needed. This will be easy for maintenance and also will enable reusability of the code.

dbconnect.php

I am using mysqli_connect() function which needs 4 parameters.

  1. server - in our case it is localhost
  2. userid - we are using root user
  3. password - no password for user root
  4. database name - demo in our case.

If connection is successful then it will return true and false otherwise. We will include this dbconnect.php in other php programs so that we do not need to write it again in the program. For detail database connection understanding please read topic How to Connect to MySQL database in PHP using mysqli_connect.

Step 3 - Develop a page to upload and view images (index.php)

This page will give users option to select one or more images (max 5), preview them and upload them. For each image a default caption will be taken from the image file name without extension. Once images are uploaded, those will be displayed as thumbnails and admin can click on any image to view larger size of the image. Also, admin can delete any image from the list.

Multiple file uplaod in PHP and Ajax

At least one image with caption needs to be selected for upload. Once uploaded, images are displayed on the right side as thumbnails. An image can be deleted by clicking on the 'x' button from top right corner of the image.

Also note that image file type and max size of the image (4M) will be validated by PHP program before upload takes place. Name of each uploaded image must be unique, uploaded image name will be the caption entered for the image. If image with same caption already uploaded, it will not allow to upload another one with same caption. Image validation is done in process_images.php program. Let's see the code for the upload form:

Form to upload images

Here, I will use 5 input image files with 5 text fields to enter caption for each image. There will be a space for previewing the image next to each input image field.

If you want to increase number of images from 5 to 10, you just need to change the counter from 5 to 10 in the for loop. A JavaScript function previewImage() is called on onChange event of the input file. Note that ids of the image file and corresponding previews are dynamic.

Display uploaded images

After upload is done, uploaded images will be displayed just on the right side of the form. Here, I am displaying uploaded images after selecting from data table 'images'.

All image names are selected from database table, named 'images'. Then in a loop, I am fetching all images and displaying them.

deleteImage() JavaScript function is called when user clicks on the delete(x) button. Modal to display the image, is defined as below and included index.php, I am using Bootstrap modal here:

modal.php

Here is the complete code for index.php

index.php

$img_dir is set as 'uploads' folder in the server. I have included process_images.php, it will be executed when form is submitted with valid data.

Step 4 - Write JavaScript/jQuery to preview image and validate form input (image_scripts.js)

Let us now see the JavaScript functions in image_scripts.js file.

Preview Image - Function ImagePreview()

This function is called as soon as admin selects an image. This function displays the preview of the image selected by the user. First parameter is the file object itself; second parameter is the id of the div where image preview will be displayed and third one is the id of the input image file. Fourth parameter is the id of the caption text. Let's see the code for this function:

A JavaScript function removeItem() with three parameters is called on onClick event of this button. This function will remove the preview and selected input file and the caption. Finally, method readAsDataURL() will create a string representation of the image URL in base64 data. This will show the image as preview after an image is selected.

Delete a Preview - Function removeItem()

This function is called when user clicks on 'x' button on the image preview as explained above.

Below is the code for removeItem() function written in image_scripts.js

Function to validate form data

We will check if any image is selected and corresponding caption is entered for at least one image before allowing form submission. validateForm() JavaScript function is called when form is submitted. If any image is selected without a caption and form is submitted, then that image will be ignored. Let's see the code for this function:

It gets the values of all image files and captions in two arrays by class names. If at least one row is found for which both image file and caption are having non empty values, it exits loop with $valid flag as true.

Step 5 - Write PHP code to upload images (process_images.php)

Upload button is used to upload the images in the server. When Upload button is clicked, form validation is done. If validation is successful, process_images.php will execute to upload the images one by one in the server and update database table after some validations. Let's see the code:

In a loop each image file and caption are processed and uploaded in "uploads" folder in the server and in the database.

Image validation

It does few validations for an image:

  1. image file extension should be in the allowed extensions list
  2. should be of valid image type and size must be of 4M (though it is not exactly 4M, you can change it anyway).
  3. if same image name (caption) already exists in the database, it will not process the image. So, caption should be unique to avoid overriding the image file in the server.

Image file name is created using the caption and extension of the selected image.

Step 6 - Scripts to view/delete an uploaded photo (image_scripts.js)

View an image in modal

After images are uploaded, those will be displayed as thumbnails. Admin can click on a image to view it and also he/she can delete a particular image by clicking on 'x' button displayed on the top right corner of an image. To view the image in modal, a modal is already defined in index.php. See below code from image_scripts.js

Remember in index.php, data-id parameter had a concatenated value of image file name and image name sent to the modal. Values are separated using split() function. So, we get the image file name and image name from array to variables. These are written in the modal body. See the image caption displayed at the bottom of the image.

Image gallery in PHP and MySQL

Delete an uploaded photo - Function deleteImage()

This function is called when admin clicks on delete (x -button) button from top right corner of an image displayed under "Uploaded Images" section of the screen. Function executes Ajax scripts to run process_images.php which deletes the image from database as well as from the server folder. After deletion, it reloads the image list. Below is the code for this function:

Here, an Ajax request is placed to run process_images.php. Let's see the code for delete section of process_images.php.

After image is deleted from database, image file needs to be deleted from the server. So, unlink() php function is used to delete the uploaded file from 'uploads' folder.

Once file is removed from server, uploaded images are refreshed

I have given complete code of image_scripts.js and process_images.php below. There is a download section, if you download the zip file, you will get all the scripts for this topic.

image_scripts.js

process_images.php

Step 7 - Write PHP code to create image gallery (gallery.php)

Now that images are uploaded and managed by admin, we can create an image gallery.

Image gallery in PHP and MySQL

This is created using very simple code. All we will be doing is to select all uploaded images and display them using Bootstrap thumbnail class. Let's see the code for gallery.php.

gallery.php

All uploaded images are selected from 'images' table and displayed as thumbnails in a loop. Image caption is displayed just below the image.

Step 8 - Add CSS (style.css)

We need to add some styles. Very simple and basic styles are used here. You can always add better styles. I have already added style.css in index.php. See below:

style.css

image gallery in phpTest the Application

Make sure in your XAMPP control panel Apache and MySQL services are running. Open the browser and run localhost/image_gallery. You will see the home page as displayed below:

Multiple photos upload in PHP and MySQL

Click on the "Select Image" buttons, select few images and see if you are able to see the preview of the images. Check the captions. Click Upload button. Images will be uploaded and you should see them on the listed on the right side with the name of each image. Click on any image, it should open in a modal. Also delete an image and see the list is refreshed.

After uploading few images, click on View Image Gallery button in the bottom of the screen. Image gallery should be displayed in a separate window.

So, this way you can upload images and display your image gallery. Hope you could understand all the steps and you could test it successfully.

image gallery in phpImportant Note

  1. For uploading images, you must verify below parameters in php.ini file. You must set file_uploads parameter to "On" in your php.ini. Also review the parameters upload_max_filesize and max_file_uploads. If you restrict file size during upload in your php program, make sure that file size is less than the size mentioned in php.ini file. Below are the values set for these parameters in my php.ini

  2. I have used minimum styles, as our main focus is on the development and not the design of the page how it should look like. There is always a scope to give the screen a better look. You can add your own stylesheet.
  3. I have given option for 5 input images, since input fields are created using a loop, you can change the loop count anytime to increase or decrease number of input images.
  4. In this application, photos are to be selected one at a time, because a caption must be entered for each photo before upload. If you do not want to give caption for each image, you can select multiple images at once and upload. You can read the topic How to upload multiple images with preview using Ajax in PHP and MySQL

image gallery in phpDownload Source Code

I have put all codes in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can directly use the code or you can modify them as per your requirements.

image gallery in phpConclusion

Uploading images and showing them in the website are very common for any web application. As an example, admin can add few images of a product with unique product names which will be displayed in the website. Note that we have used here images and captions, you can always add more fields related to a product along with the image. You can have more than one images for a product and each iamge can have name and some details.

Hope it will be useful for you.