Upload and Store video to MySQL Database with PHP

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

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

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

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 config.php file for the database configuration.

Completed Code

<?php
session_start();
$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 folder videos at the project root.

HTML

Using $_SESSION['message'] to display the file upload response. Create a file element and a submit button in the <form>.

PHP

On <form > submit assign max file size 5MB in bytes to $maxsize. You can update this value according to your requirement.

Assign file upload folder to $target_dir. Read the file extension and assign it to $extension variable.

Initialize $extensions_arr Array with valid video file extensions.

If file extension exists in $extensions_arr Array then check its file size. If it is not exceeded then upload the file and insert a new record in the videos table.

Pass $name in name field and $target_file in location field.

Completed Code

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

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

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

       // Check extension
       if( in_array($extension,$extensions_arr) ){
 
          // Check file size
          if(($_FILES['file']['size'] >= $maxsize) || ($_FILES["file"]["size"] == 0)) {
             $_SESSION['message'] = "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);
               $_SESSION['message'] = "Upload successfully.";
             }
          }

       }else{
          $_SESSION['message'] = "Invalid file extension.";
       }
   }else{
       $_SESSION['message'] = "Please select a file.";
   }
   header('location: index.php');
   exit;
} 
?>
<!doctype html> 
<html> 
  <head>
     <title>Upload and Store video to MySQL Database with PHP</title>
  </head>
  <body>

    <!-- Upload response -->
    <?php 
    if(isset($_SESSION['message'])){
       echo $_SESSION['message'];
       unset($_SESSION['message']);
    }
    ?>
    <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

Create readfile.php file to display the stored videos in the videos table.

Fetch all records from videos table.

Create <video> element where pass $location in the src attribute and use <span > to display the name.

Completed Code

<?php
include("config.php");
?>
<!doctype html>
<html>
  <head>
    <title>Upload and Store video to MySQL Database with PHP</title>
  </head>
  <body>
    <div>
 
     <?php
     $fetchVideos = mysqli_query($con, "SELECT * FROM videos ORDER BY id DESC");
     while($row = mysqli_fetch_assoc($fetchVideos)){
       $location = $row['location'];
       $name = $row['name'];
       echo "<div style='float: left; margin-right: 5px;'>
          <video src='".$location."' controls width='320px' height='320px' ></video>     
          <br>
          <span>".$name."</span>
       </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.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

54 thoughts on “Upload and Store video to MySQL Database with PHP”

  1. Please I tried your code but i want to upload up to 500 MB video please help . I eve tried other option you listed out but its not working am using WAMP SERVER

    Reply
  2. Hello,
    How can i make it to play other video format like: mwv, m4a, flv, etc.
    I put those video file extension in that extension array and yet, it does not play any of them. The video was properly uploaded and moved to the right folder.

    Reply
  3. Sir I try to upload a file of size 20MB but it always show me file is too large even I changed my XAMMP upload_max_size and post_max_filesize but it show me the smae line

    Reply
  4. The code works perfectly when uploading to the database but the comes when retrieving from the database the video doesnot play
    Any help Mr . SIngh Thank you

    Reply
  5. Hi, This is a great article 🙂 one of the first well written articles Ive found on getting an upload function and got it working first time. Just wondered, as Im using bootstrap 4, how do I get it to display a popup box, for example using a Bootstrap Modals, saying success or failure and then redirect to another page?

    Reply
  6. when i want to insert the video with a foreign key i can’t insert the data to my phpmyadmin table. How can i insert the video with a foreign key. i’m using your’s source code

    Reply
  7. Please can you make how to convert a video from other video formats to HTML5 with PHP and FFMPEG before a user uploads the video. Similar to the one above, but little different of conversion.

    Reply
  8. Hi there,

    I was hoping you could assist me with plugging some of your code into my existing code? I have the function working of uploading the file to the server (There are some issues still with the max file size, but I am hoping to sort this out with my ISP).

    I need to upload another of fields from the form to the database as well as the video file location where it is saved, as later retrieve this and show it on another page.

    Where can I share my code with you?

    Reply
  9. up to 20 mb video save to my database and folder. But when I upload 50 mb video file they didnot save in my database but save into folder. why
    my php max upload size is 128mb

    Reply
  10. NEED HELP..!!
    I have been playing with videos and trying to create a membership website for a few weeks. I just do not have it lol
    Will anyone help create a site that does what I need and help out.
    I do not have money but can advertise your programing on the site
    I need a site that allows people to login and create a profile with a picture and video.
    This is for an upcoming Virtual International Martial Arts Tournament
    They will have to pay a fee using PayPal link and once they have paid they can upload their videos.
    I then have judges 9th and 10th degree Masters and Grand Masters who will vote on the winners and they will be awarded prizes.
    So I need a way for judges to review all profiles and put a grade or ranking on each video so if we have 12 judges a spot for each judge so everyone is looked at.
    A way to pull a report of all the top winners
    Grand Champion
    20 1st place winners
    30 2nd place winners
    40 3rd place winners
    50 4th place winners
    60 5th place winners
    But then a list of all coopetitors so we can send each one a digital Certificate for competing
    I know this is beyond most programmers and is a lot to ask for free but I have seen so many tutorials that just look like this is all possible fairly easy for some of you 🙂
    Please email me if your interested
    If not I truly understand lol

    Reply
  11. Thanks alot. The code works perfectly fine – The best I’ve see so far.
    Please, can you help with deleting the file from database/directory?
    This didn’t work…
    if (isset($_POST[“btn_delete”]))
    {
    $host =” “;
    $uname =” “;
    $pwd =” “;
    $db_name =” “;
    $name = $_POST[“name”];
    $conn = mysqli_connect($host, $uname, $pwd, $db_name) or die(“Connection error: “. mysqli_error());
    $query = “DELETE FROM `videos` WHERE `name` = $name”;
    $result = mysqli_query($conn, $query);

    if($result)
    {
    echo ‘Data Deleted’;
    }else{
    echo ‘Data Not Deleted’;
    }
    mysqli_close($connect);
    }

    Reply
  12. POST Content-Length of 377970136 bytes exceeds the limit of 41943040 bytes in Unknown on line 0 ?? plese help while uploding more than 20MB size

    Reply
  13. I was wondering if what should the keyword I will search to arrange the Videos with padding, I successfully created this and all is working fine, What I want now is to add padding on each videos so they are organize like 5 videos in a row, and with a title,
    I’ve search how to tablature data in php, but doesn’t give me what I need, I hope you can give me some tips on what to search about it, thank you for this by the way, I just learned php 15 minutes ago, and I already did this. Very easy to understand tutorial.

    Reply
  14. I tried it out and works fantastic. NOW I have one problem. I want to fit this in my existing website.
    1. How do I use the style.css file to make it within my website and

    2. the name of the video to be cut at the video box and continue on next line if the name is a long one.
    Can you please show me how to do it?

    Reply

Leave a Comment