How to Upload & Download Basic Video to MySQL Database in PHP – Coding Shiksha

How to Upload & Download Basic Video to MySQL Database in PHP – Coding Shiksha

Hello Folks I am back with another blog post. In this post we will be talking about how to upload a basic video to mysql database in PHP. A video is considered to be the best form of media in the current era. So in order to store it in the database is very simple. In this post I will guide you step by step procedure in order to upload the video to mysql database. Let’s get started with building the application.

The very first thing to do is install xammp a localhost webserver in order to run this application. After downloading it just create a database called as videoupload or you can give any name to it.

 

Create Database

 

After creating the database just create a table in it called as video like this as shown below. The table will have 3 fields namely id, name,and location of the video. Make the field id as primary key of the table. It will auto increment whenever a new record is added and it will be unique.

Create Table

 

 

When you create the table the structure of the table will contain three fields namely id, name and location of the video as shown below.

 

 

After creating the table we are done with the first part of the application. Now we want to create a new directory and make a new file index.php. This file will contain the upload form where user can upload the video.

 

Upload Form

 

<!doctype html>
<html>
  <head>
    
  </head>
  <body>
    <form method="post" action="" enctype='multipart/form-data'>
      <input type='file' name='file' />
      <input type='submit' value='Upload' name='upload'>
    </form>

  </body>
</html>

 

READ  How to Download Image From URL in PHP - Coding Shiksha

This markup code contains simple upload button through which users can upload the video to the database. This is the front end of the application.

 

 

As you can see this is the simple upload button which is there to upload the video file. Now we want to write the actual PHP Logic which will be executed when the user presses the upload button.

 

Connection to Database

 

Make a new file config.php and in this php file we will writing the logic to connect to the database that we have created earlier. So write these 4 lines of code shown below to connect to the database.

 

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "videoupload"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

 

Uploading the Video

 

Now first of all create a new directory called as videos in your project root level directory so that all the videos which the user will upload will be stored in this directory. Just create this before writing any code.

After creating this directory just copy paste the following PHP code after head so that it process the video which is uploaded by the user and actually uploads it to the server.

 

<?php
    include("config.php");
 
    if(isset($_POST['upload'])){
       $maxsize = 5242880; // 5MB
 
       $name = $_FILES['file']['name'];
       $target_dir = "videos/";
       $target_file = $target_dir . $_FILES["file"]["name"];

       // Select file type
       $videoFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

       // Valid file extensions
       $extensions_arr = array("mp4","avi","3gp","mov","mpeg");

       // Check extension
       if( in_array($videoFileType,$extensions_arr) ){
 
          // Check file size
          if(($_FILES['file']['size'] >= $maxsize) || ($_FILES["file"]["size"] == 0)) {
            echo "File too large. File must be less than 5MB.";
          }else{
            // Upload
            if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){
              // Insert record
              $query = "INSERT INTO video(name,location) VALUES('".$name."','".$target_file."')";

              $query = mysqli_query($con,$query);
              if($query)
              {
              echo "Upload successfully.";
              }
            }
          }

       }else{
          echo "Invalid file extension.";
       }
 
     } 
     ?>

 

READ  How to Force a Image File to Download Automatically in PHP - Coding Shiksha

Live Uploading of Video to Database

 

 

 

 

So you can see that when we select the video and uploads it a new entry is created in the database with the name of the video and also the full path of the video also stored.Now we see the video stored in the actual videos directory as shown below.

 

 

In this processing of uploading video to the server we are checking some steps in this script before uploading this to the server. Some validations are as follows.

  • Video must be of extension (mp4,avi,mpeg,3gp,mov)
  • Video size must be less than 5MB.

So when we try to upload a video which is greater than 5MB in size. Then following error will be displayed as shown below.

 

 

 

Downloading Uploaded Videos From Server

 

Now the last thing remains which will complete this upload and read the video application. In this step we will read and display the actual uploaded videos by their location field which is stored in the database so that we can see and play the videos in the browser. Something like Video streaming application such as Youtube,Vimeo,Dailymotion etc.

READ  Implement Google Auth in PHP using cURL Http Request

Just create a separate div section in the same file below the form and copy paste the following php code into it as shown below.

 

<div>
    <?php
     $fetchVideos = mysqli_query($con, "SELECT location FROM video ORDER BY id DESC");
     while($row = mysqli_fetch_assoc($fetchVideos)){
       $location = $row['location'];
 
       echo "<div >";
       echo "<video src='".$location."' controls width='320px' height='200px' >";
       echo "</div>";
     }
     ?>
    </div>

 

Live Streaming of Uploaded Videos From Server

 

 

Full Source Code of the Application

 

Now wrapping it up all the small sections of code into one part. So copy paste the whole source code shown below to make this application work.

 

<!doctype html>
<html>
  <head>

  <?php
    include("config.php");
 
    if(isset($_POST['upload'])){
       $maxsize = 5242880; // 5MB
 
       $name = $_FILES['file']['name'];
       $target_dir = "videos/";
       $target_file = $target_dir . $_FILES["file"]["name"];

       // Select file type
       $videoFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

       // Valid file extensions
       $extensions_arr = array("mp4","avi","3gp","mov","mpeg");

       // Check extension
       if( in_array($videoFileType,$extensions_arr) ){
 
          // Check file size
          if(($_FILES['file']['size'] >= $maxsize) || ($_FILES["file"]["size"] == 0)) {
            echo "File too large. File must be less than 5MB.";
          }else{
            // Upload
            if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){
              // Insert record
              $query = "INSERT INTO video(name,location) VALUES('".$name."','".$target_file."')";

              $query = mysqli_query($con,$query);
              if($query)
              {
              echo "Upload successfully.";
              }
            }
          }

       }else{
          echo "Invalid file extension.";
       }
 
     } 
     ?>
    
  </head>
  <body>
    <form method="post" action="" enctype='multipart/form-data'>
      <input type='file' name='file' />
      <input type='submit' value='Upload' name='upload'>
    </form>

    <div>
    <?php
     $fetchVideos = mysqli_query($con, "SELECT location FROM video ORDER BY id DESC");
     while($row = mysqli_fetch_assoc($fetchVideos)){
       $location = $row['location'];
 
       echo "<div >";
       echo "<video src='".$location."' controls width='320px' height='200px' >";
       echo "</div>";
     }
     ?>
    </div>

  </body>
</html>

Leave a Reply

Close Menu