YouTube is the most popular video-sharing website that allows users to upload, view, and share videos online. If your web application has video upload functionality and you want to reduce the space of your server, upload video to YouTube will be a great idea. By uploading videos on YouTube, you will get the following facilities.
In the example YouTube video upload script, the following functionality will be implemented.
Do you want a detailed guide on Google project creation? See this tutorial – How to Create Google API Console Project
- Server space will not be consumed for video files.
- Videos can be easily embedded on the web page.
- Videos can be shared easily.
In the example YouTube video upload script, the following functionality will be implemented.
- HTML form to collect video title, description, tags, and file.
- Upload video to YouTube from PHP script with title, description, and tags.
- Embed uploaded video on the web page.
- upload_video_to_youtube_php
- google-api-php
- DB.class.php
- config.php
- index.php
- upload.php
- logout.php
- videos
Create Google Project and Enable YouTube Data API
You need to create a project and enable YouTube Data API on Google Developers Console for using Google API Client Library.- Go to the Google Developers Console.
- Select an existing project from the projects drop-down, or create a new project by clicking Create project (+):
- Enter the Project name and click Create to proceed.
- Under the Project name, you will see the Google API console has created project ID. Optionally you can change this project ID by the Edit link. But project ID must be unique worldwide.
- Click on the Create button and the project will be created in some seconds.
- Select the newly created project and enable the YouTube Data API service.
- In the sidebar, select Library under the APIs & Services section.
- Search for the YouTube Data API v3 service in the API list and select YouTube Data API v3.
- Click the ENABLE button to make YouTube Data API v3 Library available.
- In the sidebar, select Credentials under the APIs & Services section.
- Select OAuth consent screen tab. Choose an Email address, enter the Product name and click save.
- Select Credentials tab, click the Create credentials drop-down and select OAuth client ID.
- In the Application type section, select Web application.
- In the Authorized redirect URIs field, enter the redirect URL.
- Click the Create button.
- A dialog box will appear with OAuth client details, copy the Client ID and Client secret. This Client ID and Client secret allow you to access the Google APIs.
Do you want a detailed guide on Google project creation? See this tutorial – How to Create Google API Console Project
Google API Client Library for PHP
The Google API Client Library allows you to work with YouTube Data API. So, it needs to be included to access the YouTube Data API. All the required Google API PHP Client Library files are placed in the google-api-php directory.Create Database Table
You need to create a table in the database to store the video information. The following SQL creates avideos
table in the MySQL database.
CREATE TABLE `videos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`tags` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`youtube_video_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
DB Class (DB.class.php)
The DB class handles all the database related works, like fetch, insert, and update data using PHP and MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per the MySQL database credentials. Also, specify the table name ($tblName) where you want to store the video’s data.- getRow() – Retrieve the video data based on ID. If ID not given, it returns last row.
- insert() – Insert video information in the database.
- update() – Update the video information based on the ID.
<?php
class DB {
public $tblName = 'videos';
function __construct(){
// Database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'root';
$dbName = 'codexworld';
// Connect database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
function getRow($id = ''){
$con = !empty($id)?" WHERE id = $id ":" ORDER BY id DESC LIMIT 1 ";
$sql = "SELECT * FROM $this->tblName $con";
$query = $this->db->query($sql);
$result = $query->fetch_assoc();
if($result){
return $result;
}else{
return false;
}
}
function insert($title, $desc, $tags, $file_name){
$sql = "INSERT INTO $this->tblName (title,description,tags,file_name) VALUES('".$title."','".$desc."','".$tags."','".$file_name."')";
$insert = $this->db->query($sql);
return $insert?$this->db->insert_id:false;
}
function update($id, $youtube_video_id){
$sql = "UPDATE $this->tblName SET youtube_video_id = '".$youtube_video_id."' WHERE id = ".$id;
$update = $this->db->query($sql);
return $update?true:false;
}
}
?>
Google OAuth Configuration (config.php)
Inconfig.php
file, specify OAuth Client ID ($oauthClientID), OAuth Client Secret ($oauthClientSecret), Base URL ($baseURL), and Callback URL ($redirectURL), which you have generated on Google API Console.
<?php
// OAUTH Configuration
$oauthClientID = 'Your_Project_Client_ID';
$oauthClientSecret = 'Your_Project_Client_Secret';
$baseURL = 'http://localhost/upload_video_to_youtube_php/';
$redirectURL = 'http://localhost/upload_video_to_youtube_php/upload.php';
define('OAUTH_CLIENT_ID',$oauthClientID);
define('OAUTH_CLIENT_SECRET',$oauthClientSecret);
define('REDIRECT_URL',$redirectURL);
define('BASE_URL',$baseURL);
// Include google client libraries
require_once 'google-api-php/autoload.php';
require_once 'google-api-php/Client.php';
require_once 'google-api-php/Service/YouTube.php';
session_start();
$client = new Google_Client();
$client->setClientId(OAUTH_CLIENT_ID);
$client->setClientSecret(OAUTH_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setRedirectUri(REDIRECT_URL);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
?>
Video Upload Form (index.php)
In this page, an HTML form is displayed to provide the video information and select a file to upload. The upload form is submitted to theupload.php
file for further processing.
<?php
//destroy previous session data
if(session_id() != '') session_destroy();
//get file upload status
if(isset($_GET['err'])){
if($_GET['err'] == 'bf'){
$errorMsg = 'Please select a video file to upload.';
}elseif($_GET['err'] == 'ue'){
$errorMsg = 'Sorry, there was an error on uploading your file.';
}elseif($_GET['err'] == 'fe'){
$errorMsg = 'Sorry, only MP4, AVI, MPEG, MPG, MOV and WMV files are allowed.';
}else{
$errorMsg = 'Some problems occurred, please try again.';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload video to YouTube using PHP</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div class="video-box">
<h1>Upload Video to YouTube using PHP</h1>
<form method="post" enctype="multipart/form-data" action="upload.php">
<?php echo (!empty($errorMsg))?'<p class="err-msg">'.$errorMsg.'</p>':''; ?>
<label for="title">Title:</label><input type="text" name="title" value="" />
<label for="description">Description:</label> <textarea name="description" cols="20" rows="2" ></textarea>
<label for="tags">Tags:</label> <input type="text" name="tags" value="" />
<label for="file">Choose Video File:</label> <input type="file" name="file" >
<input name="videoSubmit" type="submit" value="Upload">
</form>
</div>
</body>
</html>
Upload Video to YouTube (upload.php)
Theupload.php
file handles the upload process. The following functionalities are implemented to upload video to YouTube and embed YouTube video on the website.- The file is uploaded to the local server and the information is stored in the database.
- The user needs to authenticate with their Google account.
- After authentication, the video file is uploaded to YouTube using YouTube Data API.
- YouTube video ID is updated to the database.
- On successful upload to YouTube, the video file is removed from the local server.
- The uploaded YouTube video with title, description, and tags are shown to the user.
<?php
//destroy previous session data
if(session_id() != '') session_destroy();
//get file upload status
if(isset($_GET['err'])){
if($_GET['err'] == 'bf'){
$errorMsg = 'Please select a video file to upload.';
}elseif($_GET['err'] == 'ue'){
$errorMsg = 'Sorry, there was an error on uploading your file.';
}elseif($_GET['err'] == 'fe'){
$errorMsg = 'Sorry, only MP4, AVI, MPEG, MPG, MOV and WMV files are allowed.';
}else{
$errorMsg = 'Some problems occurred, please try again.';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload video to YouTube using PHP</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div class="video-box">
<h1>Upload Video to YouTube using PHP</h1>
<form method="post" enctype="multipart/form-data" action="upload.php">
<?php echo (!empty($errorMsg))?'<p class="err-msg">'.$errorMsg.'</p>':''; ?>
<label for="title">Title:</label><input type="text" name="title" value="" />
<label for="description">Description:</label> <textarea name="description" cols="20" rows="2" ></textarea>
<label for="tags">Tags:</label> <input type="text" name="tags" value="" />
<label for="file">Choose Video File:</label> <input type="file" name="file" >
<input name="videoSubmit" type="submit" value="Upload">
</form>
</div>
</body>
</html>
Logout (logout.php)
This file is used to revoke token & destroy session data.Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
<?php
//include api config file
require_once 'config.php';
//revoke token & destroy session
$client->revokeToken();
session_destroy();
//redirect to the homepage
header("Location:index.php"); exit;
?>
Comments