Loading.......
Loading...

How to Upload Video Files using PHP and MySQLi

Posted on 24th October, 2021
VIDEO FILE UPLOAD PHP FILE UPLOAD MYSQL FILE UPLOAD PHP UPLOAD VIDEO
This tutorial teaches you how to upload and store the name of a video in a MySQL Database while the actual video file is saved in a folder on your server using PHP

The tutorial is beneficial to as many who may have designed an application that requires uploading, retrieving and displaying video files to an end user.

There are three main pages created in this tutorial which are the database_connection.php file that contains the database connection php codes, the index.php file which is made up of html form and the save_video.php file which contains the php codes that uploads the videos sent from the index.php file into a folder on your server and also save the name of the video file in a database for easy retrieval when the videos are later needed in your application.

The index.php file also shows how you can retrieve the videos using the names earlier saved in the database to get the videos from the folder where they are saved on the server.

By storing media files in a MySQL database with the actual video files saved in a folder on your server makes it easier to retrieve files uploaded by an end user or in a specific category.

DATABASE CONNECTION SCRIPT

<?php
// Fill in your databse hostname, usernme, password and database name below

$mysqli = mysqli_connect('localhost', 'root', '', 'demos'); 
if(!$mysqli)
{
	die("Error: Failed to connect to database!");
}
?>


VIDEO FILE UPLOAD HTML CODE

<div class="modal fade" id="form_modal" aria-hidden="true">
    <div class="modal-dialog">
        <form action="save_video.php" method="POST" enctype="multipart/form-data">
            <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"><span class="glyphicon glyphicon-file"></span> Upload Video File</h4>
              </div>
                <div class="modal-body">
                    <div class="col-md-3"></div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <input type="file" name="video"/>
                        </div>
                    </div>
                </div>
                <div style="clear:both;"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
                    <button name="save" class="btn btn-success"><span class="glyphicon glyphicon-save"></span> Save</button>
                </div>
            </div>
        </form>
    </div>
</div>


VIDEO FILE UPLOAD PHP SCRIPT

<?php
require_once 'database_connection.php'; // Database Connection File

// Check to be sure that the only request we can process is POST REQUEST
if(isset($_SERVER["REQUEST_METHOD"]) && strip_tags($_SERVER["REQUEST_METHOD"]) == strip_tags("POST"))
{
	if(isset($_POST['save']))
	{
		// Variable declaration
		$file_name = $_FILES['video']['name'];
		$file_temp = $_FILES['video']['tmp_name'];
		$file_size = $_FILES['video']['size'];
		
		if($file_size < 4000000) // Maximum allowed file size is 1MB
		{
			$file = explode('.', $file_name);
			$end = end($file);
			$allowed_ext = array('avi', 'wmv', 'mov', 'mp4'); // Allowed file types
			
			// If the file trying to upload is in the list of allowed file types, proceed to upload
			if( in_array($end, $allowed_ext) ) 
			{
				$actual_filename_without_extension = pathinfo($file_name, pathinfo_FILENAME);
				
				$name = str_replace(' ','-',$actual_filename_without_extension).'-'.time(); // New name to be given to the video file we are trying to upload
				$saved_location = 'video/'.$name.".".$end; // Location where the video file will be saved on our server
				
				if(move_uploaded_file($file_temp, $saved_location)) // Now try to upload the file
				{
					// Save the new file name in the database while the actual file is saved above in a folder on our server
					mysqli_query($mysqli, "insert into `video` values(0, '".mysqli_real_escape_string($mysqli, $actual_filename_without_extension)."', '".mysqli_real_escape_string($mysqli, $saved_location)."', '".mysqli_real_escape_string($mysqli, date('d-m-Y'))."')") or die(mysqli_error());
					echo "<script>alert('Great, the video was uploaded successfully')</script>";
					echo "<script>window.location = 'index.php'</script>";
				}
			}
			else // Else to not upload if its not in the list of allowed file types
			{
				echo "<script>alert('Sorry, you tried to upload a wrong video file\\n Allowed video file types are avi, wmv, mov, mp4')</script>";
				echo "<script>window.location = 'index.php'</script>";
			}
		}
		else
		{
			echo "<script>alert('Sorry, the file size you tried to upload was too large.\\nMaximum allowed file size is 4MB')</script>";
			echo "<script>window.location = 'index.php'</script>";
		}
	}
}
else 
{
	// Deny access if the request brought to this page is not a POST REQUEST
	die('Access Denied');
}
?>


DISPLAY UPLOADED VIDEO FILES SCRIPT

<?php
include 'database_connection.php'; // Database Connection File
if( mysqli_num_rows( $query = mysqli_query($mysqli, "select * from `video` order by `id` desc")) )
{
    while($fetch = mysqli_fetch_array($query))
    {
        ?>
        <div class="col-md-12">
            <div class="col-md-4" style="word-wrap:break-word;">
                <br />
                <h4>Name of Video</h4>
                <h5 class="text-primary"><?php echo $fetch['video_name']?></h5>
            </div>
            <div class="col-md-8">
                <video width="100%" height="240" controls>
                    <source src="<?php echo $fetch['file_name'];?>">
                </video>
            </div>
            <br style="clear:both;"/>
            <hr style="border-top:1px groovy #000;"/>
        </div>
         <?php
    }
}
else
{
    echo 'No video has been uploaded yet';
}
?>

START

The script is very easy to understand and customize with programming code comments to ease usability.

To see the system in action, please click on the Live Demo button below and click on the Download button to download the script if you like it.

Thank You!
The Vasplus Team.
Post Comment
Press Enter to send
No comment yet.

Submit your Job or Project Today!

We can help you turn your idea into reality, take over your existing project, or extend your current development team.

Submit your idea job or project below and we will follow up with you shortly.

OUR OBJECTIVE

Our objective is to reach a place where our services will be highly regarded by businesses from various industrial domains for building their innovative busines solutions with our cutting-edge technological expertise, interactive designs and uncompromised quality.

OUR MISSION

We aspire to help businesses ranging from startups to enterprises, who reach out to us with their requirements, in achieving great lengths, expanding their reach, upscaling their products, and generate a large user-base with our outstanding and cost-effective services.

Please Wait....
Please Wait...