Categories :

Gallery Management System in PHP8 and MySQLi

Hi, if you are a real PHP lover and love to project with raw PHP code this tutorial will help you understand lots of things on your mind. Let’s start Gallery Management System in pure PHP and MySQLi database. What you will learn after reading and practice?

  • How to create a sign up and login in PHP8
  • How to create restriction for unregistered users on your application with session
  • How to upload images using php
  • Deep knowledge on create a project with PHP8 and MySQL database
  • CRUD app in php with image uploading

Don’t worry if you are a beginner just hold it and visit our previous blogs on Basic to Advanced Tutorial on PHP – PHP Category https://webapp99.com/category/php/

Before start, you can see the demo here: DEMO LINK https://gallery.webapp99.com

Tools

I’m using XAMPP for localhost, you can use Laragon, WAMPP etc.

SQL file

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 31, 2021 at 07:56 PM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.4.13

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `gallery`
--

-- --------------------------------------------------------

--
-- Table structure for table `images`
--

CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `caption` text NOT NULL,
  `photo` varchar(255) NOT NULL,
  `user_id` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `images`
--

INSERT INTO `images` (`id`, `caption`, `photo`, `user_id`) VALUES
(4, 'Write your cfafaaption', 'download (1).jpeg', 'pranta'),
(5, 'sagsatg', 'download.jpeg', 'pranta'),
(6, 'sdgaf', 'Capture555555.PNG', 'pranta'),
(7, 'fsafgaw', 'Capture4564646.JPG', 'pialy'),
(8, 'fawfgaw', 'certificate.jpg', 'pialy');

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `email`, `password`) VALUES
(1, 'pranta', 'prantaest95@gmail.com', 'e10adc3949ba59abbe56e057f20f883e'),
(2, 'pialy', 'pialy@gmail.com', '27e692dda4c5499f7882beaa7bf6efe1');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `images`
--
ALTER TABLE `images`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`),
  ADD UNIQUE KEY `email` (`email`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `images`
--
ALTER TABLE `images`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

See the folder structure. Don’t worry to see the gallery.zip inside this image I was using this to upload on a live server.

Gallery management system in php8 and mysqli crud app in php with image upload

Now create server.php file to connect your database and basic operation for login and register. But before database operation need three files config, header and footer which is located inside includes folder.

config.php

<?php
$con = mysqli_connect("localhost:3306", "root", "", "gallery");

if (!$con) {
  die("Database is not connected successfully! Errors: ") . mysqli_error($con);
}
?>

header.php file

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gallery App</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
  </head>
  <body>
    <div class="app-container">
      

footer.php file

    <footer>
      <p>&copy;Copyright <?php echo date("Y"); ?>, Developed by <a href="https://webapp99.com">Pranta Mazumder</a></p>
    </footer>
    </div>
    <script src="js/main.js"></script>
  </body>
</html>
<?php
session_start();
require "includes/config.php";

// Initializing variables
$username = "";
$email = "email";
$errors = array();

// Register user
if (isset($_POST["reg_user"])) {
  $username = mysqli_real_escape_string($con, $_POST["username"]);
  $email = mysqli_real_escape_string($con, $_POST["email"]);
  $password_1 = mysqli_real_escape_string($con, $_POST["password_1"]);
  $password_2 = mysqli_real_escape_string($con, $_POST["password_2"]);

  // Form validation check with array_push()
  if (empty($username)) {
    array_push($errors, "Username is required");
  }
  if(empty($email)){
    array_push($errors, "Email is required");
  }
  if(empty($password_1)){
    array_push($errors, "Password is required");
  }
  if ($password_1 !== $password_2) {
    array_push($errors, "Your input passwords do not match");
  }

  if (strlen($password_1) < 6) {
    array_push($errors, "You need at least 6 digit password");
  }

  // First check to database to make sure
  // A user does not already exist with the same username and email
  $user_check_query = "SELECT * FROM users WHERE username='$username' OR email= '$email' LIMIT 1 ";
  $result = mysqli_query($con, $user_check_query);
  $user = mysqli_fetch_assoc($result);

  if($user){
    if($user["username"] === $username){
      array_push($errors, "Username already exists");
    }
    if($user["email"] === $email){
      array_push($errors, "Email already exists");
    }
  }

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1); // Encrypt the password before saving in the database
    $query = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
    mysqli_query($con, $query);
    $_SESSION["username"] = $username;
    $_SESSION["success"] = "You registration is completed, logged in now";
    header("location: index.php");
  }
}

// Login user
if (isset($_POST["login_user"])) {
  $username = mysqli_real_escape_string($con, $_POST["username"]);
  $password = mysqli_real_escape_string($con, $_POST["password"]);

  if (empty($username)) {
    // it can also easily do with html required attribute
    array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }

  if(count($errors) == 0){
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($con, $query);
    if (mysqli_num_rows($results) == 1) {
      $_SESSION["username"] = $username;
      $_SESSION["success"] = "Your are logged in";
      header("Location: gallery.php ");
    }else{
      array_push($errors, "Wrong username/password combination");
    }
  }
}

?>

index.php file

<?php
require 'server.php';
require "includes/header.php";
?>

<div class="header">
  <h2>Login</h2>
</div>

<form action="index.php" method="post">
  <?php require 'errors.php'; ?>
  <label for="username">Username</label>
  <input type="text" name="username" placeholder="Write your username">
  <label for="password">Password</label>
  <input type="password" name="password" placeholder="Write your password">
  <button type="submit" name="login_user">Sign in</button>

  <p>Not yet a member? <a href="register.php" class="sign-btn">Sign up</a> </p>

  <p>Forgot username or password? Send a mail: <a href="mailto:prantaest95@gmail.com" class="sign-btn">Gmail</a> </p>
</form>

<?php require 'includes/footer.php'; ?>

register.php file

<?php
require "server.php";
require "includes/header.php";
?>
<div>
  <h2>Register</h2>
</div>
<form action="register.php" method="post">
  <?php require "errors.php"; ?>
  <label for="username">Username</label>
  <input type="text" name="username" placeholder="Write your username" required>
  <label for="email">Email</label>
  <input type="email" name="email" placeholder="Write your email" required>
  <label for="password">Password</label>
  <input type="password" name="password_1" placeholder="Write your password" required>
  <label for="confirm_password">Confirm Password</label>
  <input type="password" name="password_2" required placeholder="Confirm your password">
  <button type="submit" name="reg_user">Sign up</button>

<p>Already have an account? <a href="index.php" class="sign-btn">Sign in</a> </p>
</form>


<?php require "includes/footer.php"; ?>

errors.php file

<?php if (count($errors) > 0): ?>
  <div class="error">
   <?php foreach ($errors as $error): ?>
     <p class="error-p"><?php echo $error; ?></p>
   <?php endforeach; ?>
  </div>
<?php endif; ?>

addphoto.php file

<?php
session_start();
require 'includes/config.php';

if (!isset($_SESSION["username"])) {
  $_SESSION["msg"] = "You must log in first";
  header("Location:index.php");
}

$target_dir = "photos/";

if(isset($_POST['submit'])){
    $caption = $_POST['caption'];
    $uploadFile = $_FILES['imageFile']['name'];
    $target_file = $target_dir . basename($uploadFile);
    $username = $_SESSION["username"];
    // deploy later
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

   if (move_uploaded_file($_FILES['imageFile']['tmp_name'], $target_file)) {
       $sql = "INSERT INTO images(caption, photo, user_id) VALUES('$caption', '$uploadFile', '$username')";
       mysqli_query($con, $sql);
   }else{
       echo "Data not inserted successfully!";
   }

   header("Location:gallery.php");
}

?>
<?php require 'includes/header.php'; ?>

<div class="header">
  <h2>Upload Photo</h2>
</div>

<form action="" method="post" enctype="multipart/form-data" class="form">

        <textarea name="caption">Write your caption</textarea><br>
        <input type="file" name="imageFile"><br>
        <button type="submit" name="submit">Upload</button>
</form>

<?php require 'includes/footer.php'; ?>

gallery.php file

<?php
session_start();
require 'includes/config.php';

if (!isset($_SESSION["username"])) {
  $_SESSION["msg"] = "You must log in first";
  header("Location:index.php");
}

if (isset($_GET["logout"])) {
  session_destroy();
  unset($_SESSION["username"]);
  header("Location:index.php");
}

$username = $_SESSION["username"];

$target_dir = "photos/";
$sql = "SELECT * FROM images WHERE user_id='$username'";
$photos = mysqli_query($con, $sql);

 ?>
<?php require 'includes/header.php'; ?>

   <?php if (isset($_SESSION["success"])): ?>
     <div class="error success">
       <h3>
         <?php echo $_SESSION["success"];
         unset($_SESSION["success"]);
         ?>
       </h3>
     </div>
   <?php endif; ?>

   <!-- Loged in user information -->
   <?php if(isset($_SESSION["username"])): ?>
     <p>Welcome <strong><?= $_SESSION["username"]; ?></strong> </p>
     <p> <a href="gallery.php?logout='1'">Logout</a> </p>
   <?php endif; ?>

 <div class="header">
   <h2>Photo Gallery</h2>
 </div>
<button type="button" name="button"> <a href="addphoto.php?username=<?= $_SESSION['username'] ?>">Add Photo</a> </button>
 <div class="gallery-content">
   <?php while ($photo = mysqli_fetch_object($photos)): ?>
    <div class="image-block">
      <img src="<?php echo $target_dir . $photo->photo; ?>" alt="<?php echo $photo->caption; ?>">
      <p><?php echo $photo->caption; ?></p>
    </div>
  <?php endwhile; ?>
 </div>


 <?php require 'includes/footer.php'; ?>

css file

*{
  box-sizing: border-box;
}
body{
  max-width: 600px;
  height: auto;
  margin: 0 auto;
  background-color: powderblue;
}
.app-container{
  margin: 10px;
  padding: 10px;
  background-color: lightblue;
  border-radius: 5px;
  box-shadow: 0px 30px 40px #888;
}
label{
  padding: 10px;
  margin: 10px;
}
input{
  margin: 10px;
  display: block;
  width: 90%;
  padding: 10px;
  box-shadow:0px 10px 14px #888;
  border: 1px solid #e6e6e6;
  border-radius: 5px;
}
textarea{
  margin: 10px;
  display: block;
  width: 90%;
  padding: 10px;
  box-shadow:0px 10px 14px #888;
  border: 1px solid #e6e6e6;
  border-radius: 5px;
}
.header h2{
  color: #333;
}
button{
  margin: 10px;
  padding: 8px;
  background-color: green;
  box-shadow: 0px 10px 14px #888;
  border: 1px solid green;
  border-radius: 5px;
  color: #fff;
  font-size: 18px;
}
p a{
  text-decoration: none;
}
footer{
  text-align: left;
  clear: both;
  padding-top: 10px;
}
p,h2,label{
  color: #333;
}

.error, .error-p{
  color: red;
}

.sign-btn {
  font-size: 18px;
  color: green;
  text-shadow: 1px 1.3px #fff;
  background-color: #e6e6e6;
  padding: 5px;
  border-radius: 4px;
  box-shadow: 0px 10px 14px #888;
}

button a{
  text-decoration: none;
  color: #fff;
}
.image-block{
  float: left;
  border-radius: 4px;
  border: 2px solid $e6e6e6;
  margin: 5px;
  box-shadow: 0px 4px 8px #888;
}
img{
  width: 250px;
  height: 250px;
  border-radius: 5px;
}
.image-block p{
  padding-left: 10px;
  padding-right: 5px;
}

Interesting thing was the main.js file was empty. Yes, I didn’t use any JavaScript even for form validation. It’s totally powered by PHP.

If you face any error leave a comment here, I will give a response with a solution.

Leave a Reply

Your email address will not be published.