Upload Video to YouTube using PHP


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.

  • Server space will not be consumed for video files.
  • Videos can be easily embedded on the web page.
  • Videos can be shared easily.

YouTube Data API provides an easy way to upload video to YouTube from the website using Google API Client Library. In this tutorial, we will show how you can upload video to YouTube from web application using PHP. Our example code will use the Google API PHP Client Library to upload video on YouTube from the website using PHP.

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.

Before get started to build a PHP script to upload video to YouTube using PHP OAuth library, take a look the files structure.

  • 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.
youtube-data-google-api-console-client-id-secret-codexworld

Note that: This Client ID and Client secret need to be specified in the script on Google API call. Also, the Authorized redirect URI needs to be matched with the redirect URL specified in the script.

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 a videos 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)

In config.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 the upload.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)

The upload.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

//include api config file
require_once 'config.php';

//include database class
require_once 'DB.class.php';

//create an object of database class
$db = new DB;

//if the form is submitted
if(isset($_POST['videoSubmit'])){
    
//video info
    
$title $_POST['title'];
    
$desc $_POST['description'];
    
$tags $_POST['tags'];
    
    
//check whether file field is not empty
    
if($_FILES["file"]["name"] != ''){
        
//file upload path
        
$fileName str_shuffle('codexworld').'-'.basename($_FILES["file"]["name"]);
        
$filePath "videos/".$fileName;
        
        
//check the file type
        
$allowedTypeArr = array("video/mp4""video/avi""video/mpeg""video/mpg""video/mov""video/wmv""video/rm");
        if(
in_array($_FILES['file']['type'], $allowedTypeArr)){
            
//upload file to local server
            
if(move_uploaded_file($_FILES['file']['tmp_name'], $filePath)){
                
//insert video data in the database
                
$insert $db->insert($title$desc$tags$fileName);
                
                
//store db row id in the session
                
$_SESSION['uploadedFileId'] = $insert;
            }else{
                
header("Location:".BASE_URL."index.php?err=ue");
                exit;
            }
        }else{
            
header("Location:".BASE_URL."index.php?err=fe");
            exit;
        }
    }else{
        
header('Location:'.BASE_URL.'index.php?err=bf');
        exit;
    }
}

// get uploaded video data from database
$videoData $db->getRow($_SESSION['uploadedFileId']);

// Check if an auth token exists for the required scopes
$tokenSessionKey 'token-' $client->prepareScopes();
if (isset(
$_GET['code'])) {
  if (
strval($_SESSION['state']) !== strval($_GET['state'])) {
    die(
'The session state did not match.');
  }

  
$client->authenticate($_GET['code']);
  
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
  
header('Location: ' REDIRECT_URL);
}

if (isset(
$_SESSION[$tokenSessionKey])) {
  
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  
$htmlBody '';
  try{
    
// REPLACE this value with the path to the file you are uploading.
    
$videoPath 'videos/'.$videoData['file_name'];
    
    if(!empty(
$videoData['youtube_video_id'])){
        
// uploaded video data
        
$videoTitle $videoData['title'];
        
$videoDesc $videoData['description'];
        
$videoTags $videoData['tags'];
        
$videoId $videoData['youtube_video_id'];
    }else{
        
// Create a snippet with title, description, tags and category ID
        // Create an asset resource and set its snippet metadata and type.
        // This example sets the video's title, description, keyword tags, and
        // video category.
        
$snippet = new Google_Service_YouTube_VideoSnippet();
        
$snippet->setTitle($videoData['title']);
        
$snippet->setDescription($videoData['description']);
        
$snippet->setTags(explode(",",$videoData['tags']));
    
        
// Numeric video category. See
        // https://developers.google.com/youtube/v3/docs/videoCategories/list
        
$snippet->setCategoryId("22");
    
        
// Set the video's status to "public". Valid statuses are "public",
        // "private" and "unlisted".
        
$status = new Google_Service_YouTube_VideoStatus();
        
$status->privacyStatus "public";
    
        
// Associate the snippet and status objects with a new video resource.
        
$video = new Google_Service_YouTube_Video();
        
$video->setSnippet($snippet);
        
$video->setStatus($status);
    
        
// Specify the size of each chunk of data, in bytes. Set a higher value for
        // reliable connection as fewer chunks lead to faster uploads. Set a lower
        // value for better recovery on less reliable connections.
        
$chunkSizeBytes 1024 1024;
    
        
// Setting the defer flag to true tells the client to return a request which can be called
        // with ->execute(); instead of making the API call immediately.
        
$client->setDefer(true);
    
        
// Create a request for the API's videos.insert method to create and upload the video.
        
$insertRequest $youtube->videos->insert("status,snippet"$video);
    
        
// Create a MediaFileUpload object for resumable uploads.
        
$media = new Google_Http_MediaFileUpload(
            
$client,
            
$insertRequest,
            
'video/*',
            
null,
            
true,
            
$chunkSizeBytes
        
);
        
$media->setFileSize(filesize($videoPath));
    
    
        
// Read the media file and upload it chunk by chunk.
        
$status false;
        
$handle fopen($videoPath"rb");
        while (!
$status && !feof($handle)) {
          
$chunk fread($handle$chunkSizeBytes);
          
$status $media->nextChunk($chunk);
        }
    
        
fclose($handle);
    
        
// If you want to make other calls after the file upload, set setDefer back to false
        
$client->setDefer(false);
        
        
// update youtube video id to database
        
$db->update($videoData['id'],$status['id']);
        
        
// delete video file from local server
        
@unlink("videos/".$videoData['file_name']);
        
        
// uploaded video data
        
$videoTitle $status['snippet']['title'];
        
$videoDesc $status['snippet']['description'];
        
$videoTags implode(",",$status['snippet']['tags']);
        
$videoId $status['id'];
    }
    
    
// uploaded video embed html
    
$htmlBody .= "<p class='succ-msg'>Video Uploaded to YouTube</p>";
    
$htmlBody .= '<embed width="400" height="315" src="https://www.youtube.com/embed/'.$videoId.'"></embed>';
    
$htmlBody .= '<ul><li><b>Title: </b>'.$videoTitle.'</li>';
    
$htmlBody .= '<li><b>Description: </b>'.$videoDesc.'</li>';
    
$htmlBody .= '<li><b>Tags: </b>'.$videoTags.'</li></ul>';
    
$htmlBody .= '<a href="logout.php">Logout</a>';

  } catch (
Google_Service_Exception $e) {
    
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
        
htmlspecialchars($e->getMessage()));
  } catch (
Google_Exception $e) {
    
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
        
htmlspecialchars($e->getMessage()));
    
$htmlBody .= 'Please reset session <a href="logout.php">Logout</a>';
  }

  
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif (
$OAUTH2_CLIENT_ID == 'REPLACE_ME') {
  
$htmlBody = <<<END
  <h3>Client Credentials Required</h3>
  <p>
    You need to set <code>\$OAUTH2_CLIENT_ID</code> and
    <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
  <p>
END;
} else {
  
// If the user hasn't authorized the app, initiate the OAuth flow
  
$state mt_rand();
  
$client->setState($state);
  
$_SESSION['state'] = $state;

  
$authUrl $client->createAuthUrl();
  
$htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="
$authUrl">authorize access</a> before proceeding.<p>
END;
}

?> <!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> <div class="uplink"><a href="<?php echo BASE_URL?>">New Upload</a></div> <div class="content"> <!-- display uploaded video info --> <?php echo $htmlBody?> </div> </div> </div> </body> </html>

Logout (logout.php)

This file is used to revoke token & destroy session data.

<?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;
?>

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

Recommended Tutorials For You

23 Comments

  1. Ali Said...
  2. Prtam Said...
  3. Rahul Said...
  4. Kufre Said...
  5. Darshan Kini Said...
  6. Pritam Saha Said...
    • CodexWorld Said...
  7. Sachin Sharma Said...
  8. Ken Said...
  9. Jos Said...
    • CodexWorld Said...
  10. Hitesh Said...
  11. Cingcow Said...
  12. Arpit Kumar Pal Said...
  13. Rajdeep Singh Said...
  14. Developer Said...
  15. Adnane Said...
  16. User Said...
  17. Ahmed Said...
  18. Lalit Said...
  19. Randhir Said...
  20. Michoul Said...
  21. Developer Said...

Leave a reply