How to Upload, Display and Delete Video Using Php and Mysql?
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:
CREATE TABLE IF NOT EXISTS `video` ( `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`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
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.
<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> <br/> <h4>1. Video Title:</h4> <input type="text" class="form-control" id="title" name="title" required> <br/> <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"/> </div> </form>
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(isset($_POST["submit"])){ if($_FILES["video"]["tmp_name"] !== "" && $_FILES["poster"]["tmp_name"] !== ""){ $result="Uploaded"; $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']; date_default_timezone_set("Asia/Kolkata"); $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')"); if($insert){ move_uploaded_file($_FILES["video"]["tmp_name"]," video/".$newfilename); move_uploaded_file($_FILES["poster"]["tmp_name"]," video/".$newfilenamePOSTER); $result="Post inserted successfully"; }else{ $result="Post insertion failed, please try again. ". mysqli_error($conn); } } }
Tip
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.
$db = new mysqli($db_host, $db_user, $db_pass, $db_name); if($db->connect_error){ 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'].'"/>; </video></div></td>'; 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.
$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); } $conn->close(); function goback() { header("Location: {$_SERVER['HTTP_REFERER']}"); exit; } goback();
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.