Sharing is caring!

Building a Powerful PHP Photo Gallery in 5 Steps

Table of Contents

Are you ready for an exciting and fulfilling journey? Let’s create a PHP-based photo gallery project together!

PHP Projects:

Picture this: a platform where users can effortlessly upload their favorite photos, organize them for easy browsing, showcase stunning galleries to share with loved ones, and even engage in lively discussions and ratings on each other’s snapshots. Sounds amazing, doesn’t it?

In this comprehensive guide, I’ll be your guide every step of the way. We’ll kick things off by setting up your local development environment, where you’ll configure a MySQL database to store all the important details.

Then, we’ll delve into the backend development, crafting PHP functions that handle everything from photo uploads to managing comments and ratings.

Finally, we’ll bring it all together with a user-friendly frontend interface, ensuring that everything looks fantastic and operates seamlessly.

Get ready to embark on this incredible journey!

Here’s a quick overview of what we’ll be doing:

StepDescription
1. SetupSet up your local development environment and project structure.
2. DatabaseConfigure a MySQL database to store user and photo information.
3. BackendWrite PHP functions for photo uploads, categorization, and gallery management.
4. FrontendCreate HTML, CSS, and JavaScript files for the user interface.
5. TestingTest the application to ensure all features work correctly and debug issues.

At the conclusion of our journey, you will possess a fully operational photo gallery that you can confidently showcase to others.

Therefore, grab a cup of coffee, make yourself comfortable, and let’s embark on the journey of crafting your very own photo gallery.

It’s going to be an enjoyable experience, and you will gain a wealth of knowledge throughout the process. Let’s begin!

php exercises
php lab exercises
php mvc folder structure best practices
php mvc framework from scratch
php mvc from scratch
php mvc project
php photo database
php photo gallery
php practice exercises
php project source code
php projects source code
php projects with source code github
php realtime chat

Prerequisites

  • PHP 7.4 or higher
  • MySQL or MariaDB
  • Web server (Apache or Nginx)
  • Basic understanding of HTML, CSS, JavaScript, and PHP

Step 1: Set Up the Project

Directory Structure

Create a directory structure for your project:

photo_gallery/
│
├── index.php
├── upload.php
├── gallery.php
├── photo.php
├── includes/
│   ├── config.php
│   ├── db.php
│   └── functions.php
├── css/
│   └── styles.css
└── js/
    └── scripts.js

Database Configuration

Create a MySQL database and the necessary tables:

CREATE DATABASE photo_gallery;

USE photo_gallery;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    email VARCHAR(100) NOT NULL
);

CREATE TABLE photos (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    title VARCHAR(100) NOT NULL,
    description TEXT,
    category VARCHAR(50),
    filename VARCHAR(255) NOT NULL,
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE comments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    photo_id INT NOT NULL,
    user_id INT NOT NULL,
    comment TEXT NOT NULL,
    comment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (photo_id) REFERENCES photos(id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE ratings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    photo_id INT NOT NULL,
    user_id INT NOT NULL,
    rating INT NOT NULL,
    rating_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (photo_id) REFERENCES photos(id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);

Config File (config.php)

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'photo_gallery');
?>

Database Connection (db.php)

<?php
require_once 'config.php';

$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>

Functions (functions.php)

<?php
require_once 'db.php';

// Function to upload photo
function uploadPhoto($userId, $title, $description, $category, $file) {
    global $link;
    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($file["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    // Check if image file is a actual image or fake image
    $check = getimagesize($file["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }

    // Check if file already exists
    if (file_exists($targetFile)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check file size
    if ($file["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($file["tmp_name"], $targetFile)) {
            $sql = "INSERT INTO photos (user_id, title, description, category, filename) VALUES (?, ?, ?, ?, ?)";
            if($stmt = mysqli_prepare($link, $sql)){
                mysqli_stmt_bind_param($stmt, "issss", $userId, $title, $description, $category, $targetFile);
                if(mysqli_stmt_execute($stmt)){
                    return true;
                } else {
                    echo "Error: Could not execute query: $sql. " . mysqli_error($link);
                }
            } else {
                echo "Error: Could not prepare query: $sql. " . mysqli_error($link);
            }
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    return false;
}

// Function to get all photos
function getPhotos() {
    global $link;
    $sql = "SELECT * FROM photos";
    $result = mysqli_query($link, $sql);
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

// Function to get photo by ID
function getPhotoById($photoId) {
    global $link;
    $sql = "SELECT * FROM photos WHERE id = ?";
    if($stmt = mysqli_prepare($link, $sql)){
        mysqli_stmt_bind_param($stmt, "i", $photoId);
        if(mysqli_stmt_execute($stmt)){
            $result = mysqli_stmt_get_result($stmt);
            return mysqli_fetch_assoc($result);
        } else {
            echo "Error: Could not execute query: $sql. " . mysqli_error($link);
        }
    } else {
        echo "Error: Could not prepare query: $sql. " . mysqli_error($link);
    }
    return null;
}

// Function to add comment
function addComment($photoId, $userId, $comment) {
    global $link;
    $sql = "INSERT INTO comments (photo_id, user_id, comment) VALUES (?, ?, ?)";
    if($stmt = mysqli_prepare($link, $sql)){
        mysqli_stmt_bind_param($stmt, "iis", $photoId, $userId, $comment);
        if(mysqli_stmt_execute($stmt)){
            return true;
        } else {
            echo "Error: Could not execute query: $sql. " . mysqli_error($link);
        }
    } else {
        echo "Error: Could not prepare query: $sql. " . mysqli_error($link);
    }
    return false;
}

// Function to get comments by photo ID
function getCommentsByPhotoId($photoId) {
    global $link;
    $sql = "SELECT * FROM comments WHERE photo_id = ?";
    if($stmt = mysqli_prepare($link, $sql)){
        mysqli_stmt_bind_param($stmt, "i", $photoId);
        if(mysqli_stmt_execute($stmt)){
            $result = mysqli_stmt_get_result($stmt);
            return mysqli_fetch_all($result, MYSQLI_ASSOC);
        } else {
            echo "Error: Could not execute query: $sql. " . mysqli_error($link);
        }
    } else {
        echo "Error: Could not prepare query: $sql. " . mysqli_error($link);
    }
    return [];
}

// Function to add rating
function addRating($photoId, $userId, $rating) {
    global $link;
    $sql = "INSERT INTO ratings (photo_id, user_id, rating) VALUES (?, ?, ?)";
    if($stmt = mysqli_prepare($link, $sql)){
        mysqli_stmt_bind_param($stmt, "iii", $photoId, $userId, $rating);
        if(mysqli_stmt_execute($stmt)){
            return true;
        } else {
            echo "Error: Could not execute query: $sql. " . mysqli_error($link);
        }
    } else {
        echo "Error: Could not prepare query: $sql. " . mysqli_error($link);
    }
    return false;
}

// Function to get average rating by photo ID
function getAverageRatingByPhotoId($photoId) {
    global $link;
    $sql = "SELECT AVG(rating) as average_rating FROM ratings WHERE photo_id = ?";
    if($stmt = mysqli_prepare($link, $sql)){
        mysqli_stmt_bind_param($stmt, "i", $photoId);
        if(mysqli_stmt_execute($stmt)){
            $result = mysqli_stmt_get_result($stmt);
            $row = mysqli_fetch_assoc($result);
            return $row['average_rating'];
        } else {
            echo "Error: Could not execute query: $sql. " . mysqli_error($link);
        }
    } else {
        echo "Error: Could not prepare query: $sql. " . mysqli_error($link);
    }
    return null;
}
?>
photo gallery php
php exercises
php exercises and solutions
php exercises and solutions pdf
php exercises online
php lab exercises
php mvc framework from scratch
php mvc from scratch

Step 2: Create the Frontend

HTML Structure (index.php)

<?php
require_once 'includes/functions.php';
$photos = getPhotos();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Photo Gallery</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
    <h1>Photo Gallery</h1>
    <a href="upload.php">Upload New Photo</a>
    <div class="gallery">
        <?php foreach($photos as $photo): ?>


 <div class="photo">
                <a href="photo.php?id=<?php echo $photo['id']; ?>">
                    <img src="<?php echo $photo['filename']; ?>" alt="<?php echo $photo['title']; ?>">
                </a>
                <p><?php echo $photo['title']; ?></p>
                <p>Average Rating: <?php echo getAverageRatingByPhotoId($photo['id']); ?></p>
            </div>
        <?php endforeach; ?>
    </div>
</body>
</html>

Upload Page (upload.php)

<?php
require_once 'includes/functions.php';

if($_SERVER["REQUEST_METHOD"] == "POST"){
    $title = $_POST['title'];
    $description = $_POST['description'];
    $category = $_POST['category'];
    $file = $_FILES['file'];

    // Assuming user_id is 1 for simplicity
    if(uploadPhoto(1, $title, $description, $category, $file)){
        header("Location: index.php");
    } else {
        echo "Error uploading photo.";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Upload Photo</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
    <h1>Upload Photo</h1>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="title">Title:</label>
        <input type="text" name="title" id="title" required>
        <br>
        <label for="description">Description:</label>
        <textarea name="description" id="description"></textarea>
        <br>
        <label for="category">Category:</label>
        <input type="text" name="category" id="category">
        <br>
        <label for="file">Photo:</label>
        <input type="file" name="file" id="file" required>
        <br>
        <input type="submit" value="Upload">
    </form>
</body>
</html>

Photo Details Page (photo.php)

<?php
require_once 'includes/functions.php';

if(isset($_GET['id'])){
    $photoId = $_GET['id'];
    $photo = getPhotoById($photoId);
    $comments = getCommentsByPhotoId($photoId);
    $averageRating = getAverageRatingByPhotoId($photoId);
}

if($_SERVER["REQUEST_METHOD"] == "POST"){
    $comment = $_POST['comment'];
    $rating = $_POST['rating'];

    // Assuming user_id is 1 for simplicity
    addComment($photoId, 1, $comment);
    addRating($photoId, 1, $rating);

    header("Location: photo.php?id=$photoId");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo $photo['title']; ?></title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
    <h1><?php echo $photo['title']; ?></h1>
    <img src="<?php echo $photo['filename']; ?>" alt="<?php echo $photo['title']; ?>">
    <p><?php echo $photo['description']; ?></p>
    <p>Category: <?php echo $photo['category']; ?></p>
    <p>Average Rating: <?php echo $averageRating; ?></p>

    <h2>Comments</h2>
    <?php foreach($comments as $comment): ?>
        <div class="comment">
            <p><?php echo $comment['comment']; ?></p>
            <p><?php echo $comment['comment_date']; ?></p>
        </div>
    <?php endforeach; ?>

    <h2>Add a Comment and Rating</h2>
    <form action="photo.php?id=<?php echo $photoId; ?>" method="post">
        <label for="comment">Comment:</label>
        <textarea name="comment" id="comment" required></textarea>
        <br>
        <label for="rating">Rating (1-5):</label>
        <input type="number" name="rating" id="rating" min="1" max="5" required>
        <br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

CSS File (styles.css)

body {
    font-family: Arial, sans-serif;
}

h1 {
    text-align: center;
}

.gallery {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    justify-content: center;
}

.photo {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: center;
}

.photo img {
    max-width: 100%;
}

.comment {
    border-top: 1px solid #ccc;
    padding-top: 10px;
    margin-top: 10px;
}

JavaScript File (scripts.js)

This file is optional if you plan to add any interactivity to your project later on.

// You can add JavaScript code here if needed for additional functionality

Step 3: Testing and Final Touches

Please perform a test on the photo upload feature:

  • Please evaluate the gallery display.
  • Please verify the comment and rating feature.
  • Enhance user management by implementing user authentication (not included in this example).
  • Enhance the design and user experience as necessary.

This basic configuration will provide you with a functional photo gallery. You can customize and enhance it further based on your specific needs, such as adding user authentication, improving the user interface, handling exceptional scenarios, and optimizing performance.

How To Run The Code?

To run your PHP-based photo gallery project, you need to set up a local development environment with a web server, PHP, and a database server. Here’s how you can do it:

Step 1: Set Up a Local Development Environment

Option 1: Using XAMPP (Windows, macOS, Linux)

Download and Install XAMPP:

Start Apache and MySQL:

  • Open the XAMPP control panel.
  • Start the Apache and MySQL services.

Create a Database:

  • Open your browser and go to http://localhost/phpmyadmin.
  • Create a new database named photo_gallery.

Option 2: Using MAMP (macOS, Windows)

Download and Install MAMP:

  • Download MAMP from MAMP.info.
  • Install MAMP on your system.

Start Servers: Open MAMP and start the servers (Apache and MySQL).

Create a Database:

  • Open your browser and go to http://localhost/phpmyadmin.
  • Create a new database named photo_gallery.

Step 2: Set Up Your Project

Project Directory: Create a directory named photo_gallery inside the htdocs directory of XAMPP or MAMP.

Copy Project Files: Copy all your project files and directories (index.php, upload.php, gallery.php, photo.php, includes, css, js) into the photo_gallery directory.

Database Configuration: Update the config.php file with your database credentials if needed:

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'photo_gallery');
?>

Step 3: Create Database Tables

Open phpMyAdmin: Open your browser and go to http://localhost/phpmyadmin.

Create Tables: Select the photo_gallery database.

Go to the SQL tab and run the following SQL queries to create the necessary tables:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    email VARCHAR(100) NOT NULL
);

CREATE TABLE photos (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    title VARCHAR(100) NOT NULL,
    description TEXT,
    category VARCHAR(50),
    filename VARCHAR(255) NOT NULL,
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE comments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    photo_id INT NOT NULL,
    user_id INT NOT NULL,
    comment TEXT NOT NULL,
    comment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (photo_id) REFERENCES photos(id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE ratings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    photo_id INT NOT NULL,
    user_id INT NOT NULL,
    rating INT NOT NULL,
    rating_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (photo_id) REFERENCES photos(id),
    FOREIGN KEY (user_id) REFERENCES users(id)
);

Step 4: Run the Project

Open your browser and go to http://localhost/photo_gallery.

Click on the “Upload New Photo” link and upload a photo to test the functionality.

Go back to the main page and view the gallery of uploaded photos.

Click on a photo to view its details and add comments and ratings.

If you want to enhance your project, you can consider including user authentication. This will allow you to manage users effectively by adding registration and login functionalities.

You will need to create new pages for user registration and login, and make necessary updates to the functions.php file to handle user authentication.

Please don’t hesitate to reach out if you have any specific concerns or require further help!

How to upload image in PHP and store in folder?

1. Get Ready to Upload!

First things first, you’ll need an HTML form (upload_form.php) where your users can select their masterpiece to upload.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Your Masterpiece</title>
</head>
<body>
    <h2>Upload Your Masterpiece</h2>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="image">
        <br><br>
        <input type="submit" value="Show the World!" name="submit">
    </form>
</body>
</html>

2. Let PHP Handle the Magic (upload.php)

Now, let PHP work its magic! This script (upload.php) will take care of the nitty-gritty details like checking if the file is a real image, making sure it’s not too big, and then whisking it away to a special folder (uploads/) for safekeeping.

<?php
// Check if the upload button was pressed
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit"])) {

    // Check if an image file was uploaded without errors
    if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) {

        $targetDir = "uploads/"; // The folder where uploaded images will live
        $targetFile = $targetDir . basename($_FILES["image"]["name"]); // Full path to the uploaded image

        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // Get the file extension

        // Allowed file types
        $allowedTypes = array("jpg", "jpeg", "png", "gif");
        if (!in_array($imageFileType, $allowedTypes)) {
            echo "Oops, sorry! Only JPG, JPEG, PNG, and GIF files are allowed.";
        } else {
            // Check file size (max 5MB)
            if ($_FILES["image"]["size"] > 5 * 1024 * 1024) {
                echo "Whoa, hold on! Your file is too large.";
            } else {
                // Move the file to its new home
                if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
                    echo "Hooray! Your masterpiece, " . htmlspecialchars(basename($_FILES["image"]["name"])). ", has been uploaded!";
                } else {
                    echo "Oops! Something went wrong and we couldn't upload your file.";
                }
            }
        }
    } else {
        echo "No file uploaded or an error occurred during upload.";
    }
}
?>
php mvc project source code
php photo database
php photo gallery
php project source code
php projects source code
php projects with source code
php real time application
php real time chat application
php realtime chat

Explanation of upload.php

Form Check: Checks if the form was submitted and the “Show the World!” button (name="submit") was clicked.

File Upload Check: Checks if an image file ($_FILES["image"]) was uploaded without errors ($_FILES["image"]["error"] == 0).

Where’s the Party?: Defines the folder ($targetDir) where the uploaded images will be stored and calculates the full path ($targetFile) to the uploaded image.

Safety First: Validates the file type against a list of approved extensions ($allowedTypes) and restricts the size to 5MB.

The Big Move: Uses move_uploaded_file() to move the file from its temporary spot ($_FILES["image"]["tmp_name"]) to its new home ($targetFile).

3. Create Your Uploads Folder

Create a folder named uploads in the same place where upload.php lives. This is where your awesome images will hang out.

4. Testing Time!

  • Put upload_form.php and upload.php on your web server.
  • Head to upload_form.php in your web browser.
  • Pick an image and click “Show the World!”

Fun Tips:

  • Always double-check file types and sizes to keep your site safe from unwanted surprises.
  • Whether it’s a silly selfie or a stunning landscape, each upload is a reason to celebrate!
  • Your PHP photo uploader isn’t just about files—it’s about sharing moments and making memories.

Now go ahead, let your users unleash their creativity, and enjoy building your PHP-powered photo uploader! Happy uploading! 📸✨

How to insert an image in PHP MySQL?

Create a form (upload_form.php) with fields for title, description, and an image upload button.

   <form action="upload.php" method="post" enctype="multipart/form-data">
       <input type="text" name="title" placeholder="Title" required><br><br>
       <textarea name="description" placeholder="Description" rows="4" cols="50"></textarea><br><br>
       <input type="file" name="image" required><br><br>
       <input type="submit" value="Upload Image" name="submit">
   </form>

PHP Script (upload.php): Handle the form submission, connect to MySQL, and insert the image data into the database.

   <?php
   // Database connection
   $conn = new mysqli("localhost", "username", "password", "database");

   // Check connection
   if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
   }

   // Process form submission
   if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit"])) {
       $title = $_POST["title"];
       $description = $_POST["description"];
       $imageData = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
       $imageType = $_FILES["image"]["type"];

       // Insert image data into database
       $sql = "INSERT INTO images (title, description, image_data, image_type)
               VALUES ('$title', '$description', '$imageData', '$imageType')";

       if ($conn->query($sql) === TRUE) {
           echo "Image uploaded successfully.";
       } else {
           echo "Error uploading image: " . $conn->error;
       }
   }

   // Close connection
   $conn->close();
   ?>

To upload files to your server, you need to have the “hp” and “upload.php” files. Once you have them, you can access “upload_form.php” in your browser. Fill out the form, choose an image, and submit it to upload the image data to MySQL.

It’s important to make sure that your PHP settings allow for sufficient file upload sizes. You can do this by adjusting the “upload_max_filesize” and “post_max_size” values.

To ensure security, it’s crucial to validate and sanitize user inputs. This will help prevent any potential security issues.

You may also need to adjust the structure of the “images” table in your database to fit the requirements of your application.

By following this method, you can store image metadata in MySQL while keeping the actual image files in a directory on your server. This approach offers flexibility and scalability for handling images in your PHP applications.

How to upload video in PHP?


Create an HTML form upload_form.php) with fields for title, description, and a file input to upload the video.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Video</title>
</head>
<body>
    <h2>Upload Video</h2>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="title">Title:</label>
        <input type="text" name="title" id="title" required>
        <br><br>
        <label for="description">Description:</label><br>
        <textarea name="description" id="description" rows="4" cols="50"></textarea>
        <br><br>
        <label for="video">Select Video:</label>
        <input type="file" name="video" id="video" required>
        <br><br>
        <input type="submit" value="Upload Video" name="submit">
    </form>
</body>
</html>


Create a PHP script (upload.php) to handle the video upload process and optionally store metadata in a database.

<?php
// Database connection details
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit"])) {
    $title = $_POST["title"];
    $description = $_POST["description"];
    $videoName = $_FILES["video"]["name"];
    $videoTemp = $_FILES["video"]["tmp_name"];
    $videoSize = $_FILES["video"]["size"];
    $videoType = $_FILES["video"]["type"];

    // Move uploaded file to a designated folder
    $uploadDir = "uploads/videos/";
    $targetFile = $uploadDir . basename($videoName);

    // Check file type
    $allowedTypes = array("video/mp4", "video/webm", "video/ogg");
    if (!in_array($videoType, $allowedTypes)) {
        echo "Sorry, only MP4, WebM, and OGG videos are allowed.";
    } else {
        // Check file size (max 100MB)
        if ($videoSize > 100 * 1024 * 1024) {
            echo "Sorry, your file is too large.";
        } else {
            // Attempt to move the uploaded file
            if (move_uploaded_file($videoTemp, $targetFile)) {
                // Optionally, insert video details into database
                // $sql = "INSERT INTO videos (title, description, file_path)
                //         VALUES ('$title', '$description', '$targetFile')";

                // if ($conn->query($sql) === TRUE) {
                //     echo "Video uploaded successfully.";
                // } else {
                //     echo "Error: " . $sql . "<br>" . $conn->error;
                // }

                echo "Video uploaded successfully.";
            } else {
                echo "Error uploading your video.";
            }
        }
    }
}

// Close connection
$conn->close();
?>

Remember to validate and sanitize user inputs for security reasons.

Double-check your PHP configuration (php.ini) to make sure file upload sizes are adequate (upload_max_filesize, post_max_size).

When saving metadata in a database, adjust your MySQL table (videos) to fit your application’s requirements.

By following this approach, you can effectively manage video uploads in PHP. Tailor and enhance it according to your project’s unique needs, like incorporating error handling, user authentication, and improving user interaction.

Conclusion

Well done on creating your very own PHP photo gallery! Now, you have a platform where your photos can stand out, neatly organized into galleries that you can easily share with friends and family.

With features like comments and ratings, it’s not just about displaying your snapshots but also about connecting and interacting with others over shared moments.

Remember, the most exciting part of building something like this isn’t just the end result—it’s the journey. You’ve mastered setting up a development environment, working with databases, and creating both backend magic and frontend finesse.

So, whether you’re capturing sunsets, selfies, or fun moments with loved ones, your PHP photo gallery is all set to make each snapshot special.

So go on, upload those memories, curate those galleries, and let your imagination run wild. Your photo gallery is more than just pixels on a screen; it’s a canvas for your memories and a way to spread happiness through snapshots.

Enjoy the process, and keep capturing those unforgettable moments!

Categories: PHP

13 Comments

Event Management System Project In PHP 2 Best Source Code · June 29, 2024 at 7:36 pm

[…] PHP Image Gallery Project Source Code […]

Building The Best Quiz Application In PHP 2024 · June 29, 2024 at 7:36 pm

[…] PHP Image Gallery Project Source Code […]

Creating Best PHP MVC Framework From Scratch 2025 · July 3, 2024 at 10:54 am

[…] PHP Image Gallery Project Source Code […]

Creación De La Best Aplicación De Prueba En PHP 2024 · July 11, 2024 at 11:12 am

[…] PHP Image Gallery Project Source Code […]

Best PHP Recipe Sharing Platform: A Step-by-Step Guide 2024 · July 20, 2024 at 3:26 pm

[…] PHP Image Gallery Project Source Code […]

How To Build The Best Job Board With PHP 2024? · July 20, 2024 at 3:26 pm

[…] PHP Image Gallery Project Source Code […]

Best Booking System In PHP With Source Code 2024 · July 20, 2024 at 7:17 pm

[…] PHP Image Gallery Project Source Code […]

Build The Best Real Time Chat Application In PHP 2024 · September 18, 2024 at 5:21 pm

[…] PHP Image Gallery Project Source Code […]

Best File Upload System With PHP Project 2024 · September 18, 2024 at 5:22 pm

[…] PHP Image Gallery Project Source Code […]

Best Social Networking Platform With PHP And React.js 2024 · September 18, 2024 at 5:24 pm

[…] PHP Image Gallery Project Source Code […]

Build Best Simple Blog Application With PHP 2024 · September 18, 2024 at 5:24 pm

[…] PHP Image Gallery Project Source Code […]

Best 5 Advanced PHP Exercises With Solutions And Explanation · September 18, 2024 at 5:25 pm

[…] PHP Image Gallery Project Source Code […]

PHP Project: URL Shortened - · September 18, 2024 at 5:28 pm

[…] PHP Image Gallery Project Source Code […]

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *