ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to Upload, Display and Delete Video Using Php and Mysql?

Updated on August 14, 2018
timothy-malche profile image

Timothy is a programming enthusiast and loves developing websites. He is an expert in HTML, CSS, JavaScript, PHP, C#, and ASP[dot]NET.

If you are planning a website that serve video tutorials, you certainly require a functionality to upload and manage video via user interface. Having user interface for uploading and managing video makes the task easier.

To store information about uploaded video MySql table is required. The following table store information about video which will be submitted via user interface. The information is video title, video file name, type of file, size in bytes, and file name of poster image for video. The structure of table is as follows:

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT 'nofile',
  `mime` varchar(50) NOT NULL DEFAULT 'text/plain',
  `size` bigint(20) unsigned NOT NULL DEFAULT '0',
  `title` varchar(350) DEFAULT NULL,
  `created` datetime NOT NULL,
  `poster` varchar(300) NOT NULL,
  PRIMARY KEY (`id`)

The code for user interface and logic for uploading video is stored in file 'video_upload.php'. For uploading video and its poster image I have used html <file> control. The poster image of video is required by html <video> control to display a preview image of video. Although it is not mandatory but it’s a good practice to have it.

Figure 1
Figure 1
<form action="video_upload.php" id="myForm" name="frmupload" method="post" enctype="multipart/form-data">
<div class="col-md-4">
  <h4>Please upload mp4 video format only.</h4>

  <h4>1. Video Title:</h4>
  <input type="text" class="form-control"  id="title" name="title" required>

  <h4>2. Featured Video:</h4>
  <input type="file" class="btn btn-info" name="video" required><br>

  <h4>3. Video Poster:</h4>
     (Please upload image file for video)<br>
  <input type="file" class="btn btn-info" name="poster" required><br>

  <input type="submit"  class="btn btn-success" name="submit"  onclick='upload_image();' value="UPLOAD"/>


After the title for video is provided in text field and file is selected using file control, upload button may be clicked which submit the details to the php code present in the same file for processing. Given below is the php code to upload video.

	if($_FILES["video"]["tmp_name"] !== "" && $_FILES["poster"]["tmp_name"] !== ""){
		$name = $conn->real_escape_string($_FILES['video']['name']);
		$mime = $conn->real_escape_string($_FILES['video']['type']);
		$data = $conn->real_escape_string(file_get_contents($_FILES  ['video']['tmp_name']));
		$size = intval($_FILES['video']['size']);
		$pname = $conn->real_escape_string($_FILES['poster']['name']);
		$pmime = $conn->real_escape_string($_FILES['poster']['type']);
		$pdata = $conn->real_escape_string(file_get_contents($_FILES  ['poster']['tmp_name']));
		$psize = intval($_FILES['poster']['size']);
		$title= $_POST['title'];

		$dataTime = date("Y-m-d H:i:s");
		$newfilename= date('dmYHis')."_".str_replace(" ", "_", basename($_FILES["video"]["name"]));
		$newfilenamePOSTER= date('dmYHis')."_".str_replace(" ", "_", basename($_FILES["poster"]["name"]));

		$insert = $conn->query("INSERT into video (name, mime, size, title, created, poster) VALUES ( '$newfilename', '$mime', '$size', '$cat',  '$dataTime',  '$newfilenamePOSTER')");
		move_uploaded_file($_FILES["video"]["tmp_name"]," video/".$newfilename);
		move_uploaded_file($_FILES["poster"]["tmp_name"]," video/".$newfilenamePOSTER);
		$result="Post inserted successfully";
			$result="Post insertion failed, please try again. ". mysqli_error($conn);


A video can be uploaded either directly in the database, or in a directory on web server. Uploading video to directory is a better option because it makes video load faster when it is displayed on web page.

The above code extract the details submitted via html form and save it to databpase. The details are title, file names, size and type. After these values are received in php code, names of video and image files are changed and stored in 'newfilename' and 'newfilenamePOSTER' variables. I have also created 'dataTime' variable to store date and time of video upload. These values are first stored in the database, and after the record is successfully inserted in database the actual files are moved for storage in 'video' folder using 'move_uploaded_file()' function provided by php.

Video can be displayed on video control which provides many rich features. In this example I am displaying all video with title and date time in tabular format. When video is displayed, its poster image will appear first, and when the play button on video control is clicked, video starts playing.

Figure 2
Figure 2
$db = new mysqli($db_host, $db_user, $db_pass, $db_name);
       die("Connection failed: " . $db->connect_error);
$result = $db->query("SELECT * FROM video order by created DESC ");
echo "<br/>";
echo "<br/>";
echo "<table width='80%' class='table-bordered table-striped table-hover' cellspacing='50px' cellpadding='50px'>";
echo "<tr><td align='center'>Video</td><td align='center'>Video Title</td><td align='center'>Date Time of Upload</td><td align='center'>Action</td></tr>";

While($row = $result->fetch_assoc())
	echo "<tr>";
	echo '<td width="250px" align="center"><br><div content="Content-Type: '.$ row ['mime'].'"> 
	<video poster=" video/'. $row['poster'] .'" width="80%" height="120" controls="controls"  >
		<source src=" video/'.$ row ['name'].'"/>;
	echo "<td align='center'>". $ row ['title'] . "</td>";
	echo "<td align='center'>". $ row ['created'] . "</td>" ;
	echo "<td align='center' width='150px'><a class='btn btn-danger' href='delete.php?id=". $ row ['id'] ."'>Delete Video</a></td>";
	echo "</tr>";
echo "</table>";

In the file for displaying video I have also added a button to delete video. The 'Delete' button makes a call to ‘delete.php’ file which deletes the video.

Figure 3
Figure 3
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

$filename = "";
$sql="SELECT * from video where id=" . $_GET['id'];
$result = $conn->query($sql);
if ($row = $result->fetch_assoc())
	$filename = $row['name'];
	$poster = $row['poster'];

$sql = "DELETE FROM video WHERE id=" . $_GET['id'];

if ($conn->query($sql) === TRUE) {
	unlink("video/" . $filename);
	unlink("video/" . $poster);

function goback()
    header("Location: {$_SERVER['HTTP_REFERER']}");

The code given above first selects the name of video and name of poster image from database table by identifying it through ‘id’ number which is supplied to it from ‘display_video.php’ file. These names are required to delete video and image files from ‘video’ folder on server. After the names are extracted, record entry will be deleted from database table by firing 'delete' Sql command. On successful deletion of record from table the related video and poster image from video folder is also deleted using 'unlink()' function.

How helpful this article is to you?

See results

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

Show Details
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)