How to upload multiple images and create image gallery in PHP
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.
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:
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:
This table stores image captions and image file names of all uploaded images
Table has 4 columns.
id - Unique id of each image, it is the primary key and auto incremented
image_name - Image name entered by the user while uploading
image_file - File name of uploaded image
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.
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.
I am using mysqli_connect() function which needs 4 parameters.
server - in our case it is localhost
userid - we are using root user
password - no password for user root
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.
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.
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.
Here is the complete code for 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.
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:
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
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.
It does few validations for an image:
image file extension should be in the allowed extensions list
should be of valid image type and size must be of 4M (though it is not exactly 4M, you can change it anyway).
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.
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.
Now that images are uploaded and managed by admin, we can create an image gallery.
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.
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:
Test 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:
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.
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
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.
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.
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.
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.