Categories
makitweb.com

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 the file to the server

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

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.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

Leave a Reply

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