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.

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` (
 `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,
) 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.
class DB {
$tblName 'videos';
// Database configuration
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword 'root';
$dbName 'semicolonworld';
// Connect database
$conn = new mysqli($dbHost$dbUsername$dbPassword$dbName);
"Failed to connect with MySQL: " $conn->connect_error);
$this->db $conn;
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();
$sql "INSERT INTO $this->tblName (title,description,tags,file_name) VALUES('".$title."','".$desc."','".$tags."','".$file_name."')";
$insert $this->db->query($sql);
$sql "UPDATE  $this->tblName SET youtube_video_id = '".$youtube_video_id."' WHERE id = ".$id;
$update $this->db->query($sql);

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.


// 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';


// Include google client libraries
require_once 'google-api-php/autoload.php'


$client = new Google_Client();

// 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.

//destroy previous session data
if(session_id() != ''session_destroy();

//get file upload status
$_GET['err'] == 'bf'){
$errorMsg 'Please select a video file to upload.';
$_GET['err'] == 'ue'){
$errorMsg 'Sorry, there was an error on uploading your file.';
$_GET['err'] == 'fe'){
$errorMsg 'Sorry, only MP4, AVI, MPEG, MPG, MOV and WMV files are allowed.';
$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.

//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
//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('semicolonworld').'-'.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");
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;

// 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'])) {
'The session state did not match.');

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

if (isset(
$_SESSION[$tokenSessionKey])) {

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
$htmlBody '';
// REPLACE this value with the path to the file you are uploading.
$videoPath 'videos/'.$videoData['file_name'];
// uploaded video data
$videoTitle $videoData['title'];
$videoDesc $videoData['description'];
$videoTags $videoData['tags'];
$videoId $videoData['youtube_video_id'];
// 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();
// Numeric video category. See
        // https://developers.google.com/youtube/v3/docs/videoCategories/list
// 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();
// 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.
// 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(
// 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);
// If you want to make other calls after the file upload, set setDefer back to false
// update youtube video id to database
// delete video file from local server
// 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>',
  } catch (
Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: 

Related Articles

Comments 0