To display dynamic image gallery using PHP and MySQL

Prerequisite: Basic Understanding of HTML, CSS, PHP and MySQL.

In this project:

  • We will create a LOGIN page where users can login to their account.                  
  • After logging in user will be provided with three options:                           
  • UPLOAD AN IMAGE
  • VIEW IMAGE GALLERY
  • LOGOUT                                                                                                                       
  • If user selects the first option to upload an image, the user will be directed to the image upload page.                                                                                              
  • If user selects the second option, the user will be directed to view image gallery page.                                                                                                                
  • If user selects the third option, the user will be simply logged out from the account and is moved to the main LOGIN page.

LOGIN PRODECURE INCLUDES THE FOLLOWING FILES: 

index.php: main login form.

process.php: where login values are processed and user account details are fetched from MySQL.

welcome.php: if the user is authenticated, the user is moved to welcome page. Welcome page consists of further options.

logout.php: User can logout and is redirected to the Login Page. 


index.php ⬇

<?php
    @session_start();
    if(isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id'])){
        header("Location:welcome.php");
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <title>LOGIN</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <style>
            .row{margin-top: 10px}
            .login_container h4{text-align: center}
            .login_container{background-color: #eeeeee; box-shadow: 10px 10px 10px #ccc; padding: 20px; width: 400px; margin-top: 10%}
            .error{color: red}
        </style>
    </head>
    <body>
        <div class="container login_container">
            <div class="row">
                <div class="col-md-12">
                    <?php
                        if(isset($_SESSION['msg']) && $_SESSION['msg'] != ''){
                            echo "<p class='error'>".$_SESSION['msg']."</p>";
                            unset($_SESSION['msg']);
                        }
                    ?>
                </div>
            </div>
            <form method="POST" action="process.php">
                <div class="row">
                    <div class="col-md-12">
                        <input type="text" class="form-control" id="email" name="email" placeholder="Enter username" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <input type="password" class="form-control" id="password" name="password" placeholder="Enter password" />
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12" style="text-align:center">
                        <button type="submit" class="btn btn-primary">LOGIN</button>
                    </div>
                </div>
            </form>
        </div>
    </body>
</html>

Explanation of Index.php

  • HTML Login Form is created with two input fields of username and password and one LOGIN Button.
<form method="POST" action="process.php">
     <input type="text" class="form-control" id="email" name="email" placeholder="Enter username" />
     <input type="password" class="form-control" id="password" name="password" placeholder="Enter password" />
     <button type="submit" class="btn btn-primary">LOGIN</button>
</form>
  • When user clicks on the LOGIN button, variables are posted to the process.php for further processing.
<form method="POST" action="process.php">
  • If session is already set, LOGIN page is not allowed to open and following instructions are coded for that.
<?php
    @session_start();
    if(isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id'])){
        header("Location:welcome.php");
    }
?>

In order to use, PHP Super Global Variable $_SESSION on any page, we need to first start the session using session_start() method. If session is set, user is moved to the Welcome Page.

  • “Users” table is created inside “mydb” database and we have also inserted some dummy rows for login. It may look like:

Where, user_id is the primary key of the table and is unique to every user.

Status : 1 refers to active users, 0 refers to the inactive users.

  • In case of any error message generated, which is supposed to be displayed on Login Page, the following error code is specified:
<?php
     if(isset($_SESSION['msg']) && $_SESSION['msg'] != ''){
           echo "<p class='error'>".$_SESSION['msg']."</p>";
           unset($_SESSION['msg']);
     }
?>

If $_SESSION[‘msg’] is set and is not void, the message is displayed on the screen and then we have unset the $_SESSION[‘msg’] variable so that, it should not display the same error message again and again on reloading.


process.php⬇

<?php
    include_once 'includes/conn.php';
    @session_start();
    $email = $_POST['email'];
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    $password = $_POST['password'];
    $sql = "SELECT * FROM users WHERE email = '".$email."' AND password = '".$password."' and STATUS = '1'";
    $exe = mysqli_query($con, $sql);
    $num_row = mysqli_num_rows($exe);
    if($num_row > 0){
        $row = mysqli_fetch_assoc($exe);
        $_SESSION['user_id'] = $row['user_id'];
        $_SESSION['username'] = $row['name'];
        $_SESSION['msg'] = '';
        header("Location:welcome.php");
    }else{
        $_SESSION['msg'] = "Invalid Username or Password";
        header("Location:index.php");
    }    
?>

Explanation of process.php

  • Connection file is included in process.php file which creates a connection with mydb database.
<?php
    $con = new mysqli("localhost","root","","mydb");
    if ($con->connect_errno) {
        echo "Failed to connect to MySQL: ".$con->connect_error;
        exit();
    }
?> 
  • Form values are posted here which are further validated and stored in local variables $email and $password.                                                                              
  • User record is fetched from the users table by using WHERE clause in MySQL Query as:
$sql = "SELECT * FROM users WHERE email = '".$email."' AND password = '".$password."' and STATUS = '1'"; 

If user record is found, SESSION variables are set and user is moved to the Welcome Page. Otherwise, error message is set and the user is moved to Login Page. 


welcome.php

<?php
    @session_start();
    if(!($_SESSION['user_id'])){
        $_SESSION['msg'] = "Please login your details.";
        header("Location:index.php");
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <title>WELCOME</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <h3>Hello, <?=ucfirst($_SESSION['username'])?></h3>
                    <h4>Welcome to our website.</h4>
                </div>
            </div>
            <div class="row" style="margin-top: 20px">
                <div class="col-md-3">
                    <button class="btn btn-primary btn-lg" onclick="window.location.href='image_upload.php'">UPLOAD IMAGE</button>
                </div>
                <div class="col-md-3">
                    <button class="btn btn-primary btn-lg" onclick="window.location.href='image_gallery.php'">VIEW GALLERY</button>
                </div>
                <div class="col-md-3">
                    <button class="btn btn-primary btn-lg" onclick="window.location.href='logout.php'">LOGOUT</button>
                </div>
            </div>
        </div>
    </body>
</html>

Explanation of welcome.php

  • If session is not set, User is moved to Login Page. This instruction is set on all the pages which are User Specific. Code may look like.                                        
  • Welcome page is coded according to the requirement of our website. We have simply displayed a welcome message to our User alongwith user’s name.                                                                                                                            
  • Three options are displayed to VIEW GALLERY, UPLOAD AN IMAGE and A LOGOUT button is also specified on this page.

logout.php⬇

<?php
    session_start();
    session_destroy();
    header("Location:index.php");
?>

Explanation of logout.php

  • session_destroy() method is used to empty all the variables in a session array. But if you want to destroy a single session variable then unset() method is used.                                                                                                                         
  • Header() in-built PHP method is used to redirect the user to Login Page.

IMAGE UPLOADING INCLUDES THE FOLLOWING FILE:

  • image_upload.php

image_upload.php⬇

<?php
    session_start();
    if(!isset($_SESSION['user_id']) || $_SESSION['user_id'] <= 0){
        header("Location:index.php");
    }
    include_once 'includes/conn.php';
    $msg = "";
    if (isset($_POST['upload'])) {
        $error = 0;
        $filename = $_FILES["image"]["name"];
        $tempname = $_FILES["image"]["tmp_name"];
        $path = "images/".$filename;   
        $extension = pathinfo($filename, PATHINFO_EXTENSION);    
        // VALIDATIONS
        $allowed_ext = array("png", "jpg", "jpeg");
        $size = $_FILES["image"]["size"];
        $file = "images/".$filename;
        if(!in_array($extension, $allowed_ext)){
            $_SESSION['msg'] = "Only JPEG and PNG images are allowed";
            $error = 1;
        }elseif($size > 1000000){
            $_SESSION['msg'] = "Size cannot exceed 1MB";
            $error = 1;
        }
        if($error == 0){
            if(file_exists($file)){
                $filename = time().".".$extension;   // rename if file already exists.
            }
            if(move_uploaded_file($_FILES['image']['tmp_name'], 'images/'.$filename)){
                $sql = "INSERT INTO upload(user_id, filename, created_at) VALUES ('".$_SESSION['user_id']."','$filename', '".date('Y-m-d H:i:s')."')";
                mysqli_query($con, $sql);
                $_SESSION['msg'] = "<p class='success'>Image uploaded successfully.</p>";
            }else{
                $_SESSION['msg'] = "<p class='failure'>Failed to upload image.</p>";
            }
        }else{
            $_SESSION['msg'] = "<p class='failure'>".$_SESSION['msg']."</p>";
        }
    }
 ?>
<!DOCTYPE html>
<html>
    <head>
        <title>Image Upload</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <style>
            .wrapper{margin: 20px 50px;}
            p{margin: 10px}
            .success{color: green}
            .failure{color: red}
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div>
                <?php
                    if(isset($_SESSION['msg']) && $_SESSION['msg'] != ''){
                        echo $_SESSION['msg'];
                        unset($_SESSION['msg']);
                    }
                ?>
            </div>
            <form method="POST" id="imageUploadForm" action="image_upload.php" enctype="multipart/form-data">
                <input type="file" name="image" value="" accept="image/*"><br>
                <button type="submit" value="" class="btn btn-primary" name="upload" id="upload">UPLOAD</button>        
            </form>
        </div>
    </body>
</html> 

 

  1.  
<form method="POST" action="" enctype="multipart/form-data">
            <input type="file" name="image" value="" accept="image/*"><br>
            <button type="submit" value="" class="btn btn-primary" name="upload">UPLOAD</button>        
</form>

• A form is created having input type “file”.

• multipart/form-data is used as a form element whenever a form is having a file upload option.

accept="image/*" refers to image file type to be displayed to the user in dialog selection box.

 

if (isset($_POST['upload'])) {
        $filename = $_FILES["image"]["name"];
        $tempname = $_FILES["image"]["tmp_name"];
        $path = "images/".$filename;   
        $sql = "INSERT INTO upload(filename, created_at) VALUES ('$filename', '".date('Y-m-d H:i:s')."')";
        mysqli_query($con, $sql);       
        if(move_uploaded_file($tempname, $path)){
            $msg = "<p class='success'>Image uploaded successfully.</p>";
        }else{
            $msg = "<p class='failure'>Failed to upload image.</p>";
        }
    } 

DESCRIPTION

$_FILES supervariable is used to access the various elements related to the image to upload.

$_FILES[“image”] where, image is the value of the name element of image input tag.   

<input type="file" name="image" value="" accept="image/*">

$_FILES[“image”][“name”] carries the original name of the file.

$_FILES[“image”][“tmp_name”] carries the temporary name of the uploaded file/image which is generated by PHP.

$path defines the path name where to store the image on the server.

• move_uploaded_file($tempname, $path)

     this in-built method is used to move the image or file to the server.


IMAGE GALLERY INCLUDES THE FOLLOWING FILE:

  • image_gallery.php

image_gallery.php⬇

<?php
include_once 'includes/conn.php';
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] <= 0) {
    header("Location:index.php");
}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Image Gallery</title>
        <link rel="stylesheet" href="css/bootstrap.css">
        <script src="js/bootstrap.js"></script>
        <style>
            ul{position: fixed; bottom: 50px; left: 40%}
            ul li{margin-right: 5px; padding: 10px; background-color: #eee; border-radius: 5px;}
            ul li a{text-decoration: none}
        </style>
    </head>
    <body>
        <div class="row">
            <div class="col-md-12" style="padding:10px">
                <a href="welcome.php" style="margin-left:20px">HOME</a>
            </div>
        </div>
        <div class="row" style="background-color:#000; padding: 15px">
            <?php
            if (isset($_GET['pageno'])) {
                $page_no = $_GET['pageno'];
            } else {
                $page_no = 1;
            }
            $records_per_page = 8;
            $offset = ($page_no - 1) * $records_per_page;
            $total = "SELECT COUNT(*) FROM upload";
            $result = mysqli_query($con, $total);
            $total_rows = mysqli_fetch_array($result)[0];
            $total_pages = ceil($total_rows / $records_per_page);
 
            $sql = "SELECT * FROM upload WHERE user_id = '" . $_SESSION['user_id'] . "' LIMIT $offset, $records_per_page";
            $result = mysqli_query($con, $sql);
            while ($row = mysqli_fetch_assoc($result)) {
                echo '<div class="col-lg-3 col-md-4 col-6">
                <a href="#" class="d-block mb-4 h-100">
                    <img class="img-fluid img-thumbnail" src="images/' . $row['filename'] . '" alt="">
                </a>
            </div>';
            }
            echo '</table>';
            ?>
        </div>
        <ul class="pagination">
            <li><a href="?pageno=1">First</a></li>
            <li class="<?php if ($page_no <= 1){ echo 'disabled'; } ?>">
                <a href="<?php  if ($page_no <= 1) {
                                    echo '#';
                                }else{
                                    echo "?pageno=" . ($page_no - 1);
                                }?>">
                    Prev
                </a>
            </li>
            <li class="<?php if ($page_no >= $total_pages){ echo 'disabled'; } ?>">
                <a href="<?php if ($page_no >= $total_pages) {
                                    echo '#';
                                }else{
                                    echo "?pageno=" . ($page_no + 1);
                                } ?>">
                    Next
                </a>
            </li>
            <li><a href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
        </ul>
    </body>
</html> 

 

  • SELECT SQL statement is used to fetch the images of particular user by using user_id = $_SESSION[‘user_id’] from the upload table. 
$sql = "SELECT * FROM upload WHERE user_id = '" . $_SESSION['user_id'] . "' LIMIT $offset, $records_per_page";
  • Images are displayed using the following code:
<a href="#" class="d-block mb-4 h-100">
                    <img class="img-fluid img-thumbnail" src="images/' . $row['filename'] . '" alt="">
                </a>

We have also applied pagination to the view.


Summary

In this project, we have learned to create a Image gallery using HTML, PHP and CSS. A user is logged in to his account and then a user is allowed upload as many images a user wants to. In order to view the uploaded images, an image gallery is created where all the images of logged in user are displayed using pagination.

Help Us to Improve our content

Let's Talk
Go back to Previous Course