Upload and Store video to MySQL Database with PHP

By storing media files to MySQL database make easier to retrieve files uploaded by the user or in the specific category.

For this require storing file to the server and save the reference to the database.

In the tutorial, I show how you can upload and store video to MySQL database table with PHP.

Upload and store video to MySQL database with PHP


Contents

  1. Table structure
  2. Configuration
  3. Upload and Store Video
  4. Read Videos
  5. Conclusion

 


1. Table structure

I am using videos table in the example.

CREATE TABLE `videos` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `location` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Configuration

Create a new config.php file.

Completed Code

<?php

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

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

3. Upload and Store Video

Create a new directory videos in the project root.

HTML

Create a file element and a submit button in the <form>.

PHP

On <form> submit check file extension is valid or not and also check file size is not greater than 5MB.

Upload the file to videos directory and insert file name and location in videos table.

Completed Code

<!doctype html>
<html>
  <head>
    <?php
    include("config.php");
 
    if(isset($_POST['but_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 videos(name,location) VALUES('".$name."','".$target_file."')";

              mysqli_query($con,$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='but_upload'>
    </form>

  </body>
</html>

4. Read Videos

Fetch records from videos table and select location field.

Create <video> element where pass $location in the src attribute.

Completed Code

<?php
include("config.php");
?>
<!doctype html>
<html>
  <head>
    <style>
    video{
     float: left;
    }
    </style>
  </head>
  <body>
    <div>
 
     <?php
     $fetchVideos = mysqli_query($con, "SELECT location FROM videos 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>

5. Conclusion

Store video file in a directory and insert file location in a MySQL database table. Display file using <video> element.

Before setting max file size for file size validation make sure to check post_max_size and upload_max_filesize in php.ini file and update it accordingly if required.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 2
  •  
  •  
  •  
  •  
  •  

11 Comments

  1. $maxsize = 5242880; // 5MB
    How much is this? I did not understand what this conversion is.
    5242880

    September 15, 2018
    Reply
    • Yogesh Singh said:

      Hi Lucas,
      The conversion is in Bytes.
      $_FILES[‘file’][‘size’] returns values in Bytes.

      September 15, 2018
      Reply
  2. dun said:

    Hello,thanks for sharing the code.I want to be able to upload videos of less than 500 MBs how do i go about it.Thank you

    October 12, 2018
    Reply
    • Yogesh Singh said:

      Replace $maxsize value with this 524288000 (500 MB in bytes).

      October 12, 2018
      Reply
      • dun said:

        after changing the maxsize to 524288000 i am still unable to upload this video file of 2.93 MB (3,074,047 bytes)

        October 12, 2018
        Reply
        • Yogesh Singh said:

          I think your upload and post size is defined low.

          Find this two values – upload_max_filesize, post_max_size in php.ini.

          Replace it with 510M.

          Save and restart the server.

          If you still facing the problem you can mail me the code at makitweb@gmail.com I will check it.

          October 12, 2018
          Reply
  3. Dries said:

    Hi If i have multiple images or videos it only shows the last one. How do i fix this?

    Kind regards

    Dries

    October 24, 2018
    Reply
    • Yogesh Singh said:

      Hi Dries,
      You can view this tutorial for multiple uploading. You need to update the code accordingly.

      October 25, 2018
      Reply
  4. nisar said:

    sir video is not showing mean there is a voice and audio player just how can i fix this

    November 27, 2018
    Reply
  5. Hakim Ehsan said:

    Thank You!
    It was very useful.

    March 14, 2019
    Reply

Leave a Reply

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