Image gallery or photo gallery is a special feature of web applications that allows users to upload images and access their images. If you’re working on a web project and want to implement users image gallery then your at right place.
In this tutorial you will learn how to create dynamic photo gallery using PHP and MySQL. You will also learn how to create lightbox with image in gallery to increase user experience as it helps to display images in larger size when click on it.
In this tutorial we will use jQuery plugin Lightbox2 for lightbox.
Also, read:
- Upload Multiple Images using jQuery, PHP & MySQL
- Reduce or Compress Image Size While Uploading in PHP
- Image Upload without Page Refresh with PHP and jQuery
So let’s start the coding. We will have following file structure to creating image gallery using PHP MySQL.
- index.php
- user.php
- upload.php
- gallery.php
- logout.php
Steps1: Create Database Tables
As we will handle image gallery example with user login to create theri image gallery by uploading images. So we will create user table usign below table create query.
CREATE TABLE `user` ( `id` int(11) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, `first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT NULL, `mobile` int(11) NOT NULL, `address` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `user` ADD PRIMARY KEY (`id`); ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
We will insert a user record to login with user to manage their image galllery.
INSERT INTO `user` (`id`, `email`, `password`, `first_name`, `last_name`, `mobile`, `address`) VALUES (2, 'smith@phpzag.com', '202cb962ac59075b964b07152d234b70', 'Adam', 'Smith', 2147483647, '');
We will also create user_gallery table using below query to store uploaded image details.
CREATE TABLE `user_gallery` ( `id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `image_title` varchar(255) NOT NULL, `image_description` varchar(255) NOT NULL, `image_name` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `user_gallery` ADD PRIMARY KEY (`id`); ALTER TABLE `user_gallery` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
Steps2: Create Login Form
We will create login form in index.php for user login to access user section to allow access to manage gallery.
<div class="container"> <h2>Create Dynamic Image Gallery with jQuery, PHP & MySQL</h2> <div class="row"> <div class="col-md-4 col-md-offset-4 well"> <form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform"> <fieldset> <legend>Login</legend> <div class="form-group"> <label for="name">Email</label> <input type="text" name="email" placeholder="Your Email" required class="form-control" /> </div> <div class="form-group"> <label for="name">Password</label> <input type="password" name="password" placeholder="Your Password" required class="form-control" /> </div> <div class="form-group"> <input type="submit" name="login" value="Login" class="btn btn-primary" /> </div> </fieldset> </form> </div> </div> </div>
Steps3: Implement User Login
We will handle user login functionality on login form submit using below code and redirect to gallery.php to access user gallery. We will call method login() from User.php class.
<?php $loginMessage = ''; if(!empty($_POST["login"]) && !empty($_POST["email"]) && !empty($_POST["password"])) { $user->email = $_POST["email"]; $user->password = $_POST["password"]; if($user->login()) { header("Location: gallery.php"); } else { $loginMessage = 'Invalid login! Please try again.'; } } ?>
We will implement method login() in class User.php to handle user login.
public function login(){ if($this->email && $this->password) { $sqlQuery = " SELECT * FROM ".$this->userTable." WHERE email = ? AND password = ?"; $stmt = $this->conn->prepare($sqlQuery); $password = md5($this->password); $stmt->bind_param("ss", $this->email, $password); $stmt->execute(); $result = $stmt->get_result(); if($result->num_rows > 0){ $user = $result->fetch_assoc(); $_SESSION["userid"] = $user['id']; $_SESSION["name"] = $user["first_name"]." ".$row["last_name"]; return 1; } else { return 0; } } else { return 0; } }
Steps4: Create Image Upload Form
In upload.php, we will design image upload Form with view image gallery link.
<div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4 well"> <strong><a href="gallery.php">View Image Gallery</a> </strong> <a href="logout.php">Logout</a> <br><br> <form role="form" enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <fieldset> <legend>Upload Images</legend> <div class="form-group"> <label for="name">Image Title</label> <input type="text" name="image_title" placeholder="Image Title" class="form-control" /> </div> <div class="form-group"> <label for="name">Image Description:</label> <input type="text" name="img_description" placeholder="Image Description" class="form-control" /> </div> <div class="form-group"> <label for="name">Choose Image:</label> <input type="file" name="uploaded_file" placeholder="Choose file" class="form-control" /> </div> <div class="form-group"> <input type="submit" name="upload" value="upload" class="btn btn-primary" /> </div> </fieldset> </form> </div> </div> </div>
Steps5: Implement Image Upload
Now will handle image upload functionality in upload.php and also insert uploaded image details in database table user_gallery
<?php if(isset($_POST["upload"]) && $_SESSION["userid"]) { $image_title=$_POST["image_title"]; $img_description=$_POST["img_description"]; $fk_uid=$_SESSION["userid"]; $image_name=$_FILES["uploaded_file"]["name"]; if ($_FILES["uploaded_file"]["type"]=="image/gif" || $_FILES["uploaded_file"]["type"]=="image/jpeg" || $_FILES["uploaded_file"]["type"]=="image/pjpeg" || $_FILES["uploaded_file"]["type"]=="image/png" && $_FILES["uploaded_file"]["size"]<20000) { if ($_FILES["uploaded_file"]["error"]>0) { echo "Return Code:".$_FILES["uploaded_file"]["error"]."
"; } else { $i=1; $success = false; $new_image_name=$image_name; while(!$success) { if (file_exists("uploads/".$new_image_name)) { $i++; $new_image_name="$i".$image_name; } else { $success=true; } } move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"uploads/".$new_image_name); $gallery->image_title = $image_title; $gallery->description = $img_description; $gallery->image_name = $image_name; $gallery->insert(); $message = "Image uploaded successfully."; } } else { echo "Invalid file"; } } ?>
Steps6: Display Images in User Gallery
Now in gallery.php, we will display uploaded images in user gallery. We will call method getGalleryList() in class Gallery.php to get list of gallery images. Then we will loop through images to display. We will also use data-lightbox attribute with anchor to display gallery image in lightbox when click on image.
<ul> <?php $galleryList = $gallery->getGalleryList(); while ($image = $galleryList->fetch_assoc()) { ?> <li id="gallery_image_<?php echo $image["id"]; ?>"> <span><?php echo $image["image_description"]; ?></span><br> <a href="uploads/<?php echo $image["image_name"]; ?>" data-lightbox="<?php echo $_SESSION['userid']; ?>" data-title="<?php echo $image["image_title"]; ?>"><img src="uploads/<?php echo $image["image_name"]; ?>" class="images" width="200" height="200"></a> <br><br> <span class="pull-right"> <a href="" id="<?php echo $image["id"]; ?>" class="delete"><span class="glyphicon glyphicon-trash"></span></a> </span> </li> <?php } ?> </ul>
We will implement method getGalleryList() in class Gallery.php to get list of gallery.
function getGalleryList(){ $sqlQuery = " SELECT id, user_id, image_title, image_description, image_name FROM ".$this->userGalleryTable." WHERE user_id='".$_SESSION["userid"]."'"; $stmt = $this->conn->prepare($sqlQuery); $stmt = $this->conn->prepare($sqlQuery); $stmt->execute(); $result = $stmt->get_result(); return $result; }
Steps7: Implement User Logout
As we have handle user login using SESSION in multiple pages, so handle user logout functionality by SESSION destroy.
<?php session_start(); session_destroy(); header("location:index.php"); ?>
You may also like:
- Build Live Chat System with Ajax, PHP & MySQL
- Create Event Calendar with jQuery, PHP and MySQL
- Build Invoice System with PHP & MySQL
- Push Notification System with PHP & MySQL
- Create Bootstrap Cards with PHP and MySQL
- Build Content Management System with PHP & MySQL
- Convert Unix Timestamp To Readable Date Time in PHP
- Ajax Drop Down Selection Data Load with PHP & MySQL
- Inventory Management System with Ajax, PHP & MySQL
- Drag and Drop File Upload using jQuery and PHP
- Load Dynamic Content in Bootstrap Popover with Ajax, PHP & MySQL
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download
Hi,
I tried implementing your code, however it is not even logging when used a server. It just redirects back to index.php file. Not sure what the issue is. Could you suggest what it could be ? Thanks
I have just checked demo and its working fine. Debug your code and check if login form submit work and header redirected to user.php after successful login. If its still not working then send your code, I will try to fix your issue. thanks!
very good logic but you have to give the edit and update functionality.
i always this message:Warning: session_start(): Cannot send session cache limiter
Check if there a space in front of the
i always get (database error: Incorrect integer value: ” for column ‘id’ at row 1) everytime i click the upload
May be it missing to be primary key and auto increment, you can make these. thanks!