PHP Upload Videos on Youtube Using Developer API

PHP Upload Videos on Youtube Using Developer API

PHP Upload Videos on Youtube

 
In this article we are going to upload videos on Youtube using PHP. For this we are using google api php client version 1.0.5. If you are using this as a reference then please use the same version. Let's start first we need to create our Project on google developer console.
 
Create Project
Step - 1: Visit https://console.developers.google.com/start Create a new project.
Step - 2: Then go to Menu and Select API Manager from the left.
Step - 3: From the right pan click on YouTube Data API. In new window click on Enable API button.
Step - 4: Now we need to create credential to access this API. Click on Credential from the left menu pan. From the right pan click on New credentials button and select 0Auth client ID. In new windows Select Web application as Application type. Name: <YourAppName>, Authorized JavaScript origins: http://<YourDomain>, Authorized redirect URIs: http://<YourDomain>/Youtube/Authenicate.php. Once done click on Create button to create 0Auth client ID.
Step - 5: Save your client ID xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com and client secret key xxxxxxxxxxxxxxxxxxxxxxxx.
Step - 6: Finally we created our 0Auth client ID in last just click on 0Auth consent screen. Provide Email address and Product name shown to users.
 
We have our 0Auth client ID next we need to get the refresh token follow below step to get Refresh Token.
Step - 2: Extract folder Google and placed it at http://<DomainName>/YoutTube/Google
Step - 3: Create Authenticate.php http://<DomainName>/YoutTube/Authenticate.php and copy below code.
&lt;?php

//error_reporting(1);

// Call set_include_path() as needed to point to your client library.
ini_set(&#39;include_path&#39;, $_SERVER[&quot;DOCUMENT_ROOT&quot;].&quot;/Youtube&quot;);
require_once $_SERVER[&quot;DOCUMENT_ROOT&quot;].&quot;/Youtube/Google/Client.php&quot;;
require_once $_SERVER[&quot;DOCUMENT_ROOT&quot;].&quot;/Youtube/Google/Service/YouTube.php&quot;;
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} &lt;{{ https://cloud.google.com/console }}&gt;
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * &lt;https://developers.google.com/youtube/v3/guides/authentication&gt;
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = &#39;Replace This&#39;;
$OAUTH2_CLIENT_SECRET = &#39;Replace This&#39;;
$REDIRECT = &#39;Replace This&#39;;
$APPNAME = &quot;Replace This&quot;;
$client = new Google_Client();
$client-&gt;setClientId($OAUTH2_CLIENT_ID);
$client-&gt;setClientSecret($OAUTH2_CLIENT_SECRET);
$client-&gt;setScopes(&#39;https://www.googleapis.com/auth/youtube&#39;);
$client-&gt;setRedirectUri($REDIRECT);
$client-&gt;setApplicationName($APPNAME);
$client-&gt;setAccessType(&#39;offline&#39;);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

if (isset($_GET[&#39;code&#39;]))
{
    if (strval($_SESSION[&#39;state&#39;]) !== strval($_GET[&#39;state&#39;]))
    {
        die(&#39;The session state did not match.&#39;);
    }

    $client-&gt;authenticate($_GET[&#39;code&#39;]);
    $_SESSION[&#39;token&#39;] = $client-&gt;getAccessToken();

}

if (isset($_SESSION[&#39;token&#39;]))
{
    $client-&gt;setAccessToken($_SESSION[&#39;token&#39;]);
    echo &#39;&lt;code&gt;&#39; . $_SESSION[&#39;token&#39;] . &#39;&lt;/code&gt;&#39;;
}

// Check to ensure that the access token was successfully acquired.
if ($client-&gt;getAccessToken()) {
    try {
        // Call the channels.list method to retrieve information about the
        // currently authenticated user&#39;s channel.
        $channelsResponse = $youtube-&gt;channels-&gt;listChannels(&#39;contentDetails&#39;, array(
            &#39;mine&#39; =&gt; &#39;true&#39;,
        ));

        $htmlBody = &#39;&#39;;
        foreach ($channelsResponse[&#39;items&#39;] as $channel) {
            // Extract the unique playlist ID that identifies the list of videos
            // uploaded to the channel, and then call the playlistItems.list method
            // to retrieve that list.
            $uploadsListId = $channel[&#39;contentDetails&#39;][&#39;relatedPlaylists&#39;][&#39;uploads&#39;];

            $playlistItemsResponse = $youtube-&gt;playlistItems-&gt;listPlaylistItems(&#39;snippet&#39;, array(
                &#39;playlistId&#39; =&gt; $uploadsListId,
                &#39;maxResults&#39; =&gt; 50
            ));

            $htmlBody .= &quot;&lt;h3&gt;Videos in list $uploadsListId&lt;/h3&gt;&lt;ul&gt;&quot;;
            foreach ($playlistItemsResponse[&#39;items&#39;] as $playlistItem) {
                $htmlBody .= sprintf(&#39;&lt;li&gt;%s (%s)&lt;/li&gt;&#39;, $playlistItem[&#39;snippet&#39;][&#39;title&#39;],
                    $playlistItem[&#39;snippet&#39;][&#39;resourceId&#39;][&#39;videoId&#39;]);
            }
            $htmlBody .= &#39;&lt;/ul&gt;&#39;;
        }
    } catch (Google_ServiceException $e) {
        $htmlBody .= sprintf(&#39;&lt;p&gt;A service error occurred: &lt;code&gt;%s&lt;/code&gt;&lt;/p&gt;&#39;,
            htmlspecialchars($e-&gt;getMessage()));
    } catch (Google_Exception $e) {
        $htmlBody .= sprintf(&#39;&lt;p&gt;An client error occurred: &lt;code&gt;%s&lt;/code&gt;&lt;/p&gt;&#39;,
            htmlspecialchars($e-&gt;getMessage()));
    }

    $_SESSION[&#39;token&#39;] = $client-&gt;getAccessToken();
} else {
    $state = mt_rand();
    $client-&gt;setState($state);
    $_SESSION[&#39;state&#39;] = $state;

    $authUrl = $client-&gt;createAuthUrl();
    $htmlBody = &lt;&lt;&lt;END
  &lt;h3&gt;Authorization Required&lt;/h3&gt;
  &lt;p&gt;You need to &lt;a href=&quot;$authUrl&quot;&gt;authorise access&lt;/a&gt; before proceeding.&lt;p&gt;
END;
}
&lt;?php

//error_reporting(1);

// Call set_include_path() as needed to point to your client library.
ini_set(&#39;include_path&#39;, $_SERVER[&quot;DOCUMENT_ROOT&quot;].&quot;/Youtube&quot;);
require_once $_SERVER[&quot;DOCUMENT_ROOT&quot;].&quot;/Youtube/Google/Client.php&quot;;
require_once $_SERVER[&quot;DOCUMENT_ROOT&quot;].&quot;/Youtube/Google/Service/YouTube.php&quot;;
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} &lt;{{ https://cloud.google.com/console }}&gt;
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * &lt;https://developers.google.com/youtube/v3/guides/authentication&gt;
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = &#39;Replace This&#39;;
$OAUTH2_CLIENT_SECRET = &#39;Replace This&#39;;
$REDIRECT = &#39;Replace This&#39;;
$APPNAME = &quot;Replace This&quot;;
$client = new Google_Client();
$client-&gt;setClientId($OAUTH2_CLIENT_ID);
$client-&gt;setClientSecret($OAUTH2_CLIENT_SECRET);
$client-&gt;setScopes(&#39;https://www.googleapis.com/auth/youtube&#39;);
$client-&gt;setRedirectUri($REDIRECT);
$client-&gt;setApplicationName($APPNAME);
$client-&gt;setAccessType(&#39;offline&#39;);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

if (isset($_GET[&#39;code&#39;]))
{
    if (strval($_SESSION[&#39;state&#39;]) !== strval($_GET[&#39;state&#39;]))
    {
        die(&#39;The session state did not match.&#39;);
    }

    $client-&gt;authenticate($_GET[&#39;code&#39;]);
    $_SESSION[&#39;token&#39;] = $client-&gt;getAccessToken();

}

if (isset($_SESSION[&#39;token&#39;]))
{
    $client-&gt;setAccessToken($_SESSION[&#39;token&#39;]);
    echo &#39;&lt;code&gt;&#39; . $_SESSION[&#39;token&#39;] . &#39;&lt;/code&gt;&#39;;
}

// Check to ensure that the access token was successfully acquired.
if ($client-&gt;getAccessToken()) {
    try {
        // Call the channels.list method to retrieve information about the
        // currently authenticated user&#39;s channel.
        $channelsResponse = $youtube-&gt;channels-&gt;listChannels(&#39;contentDetails&#39;, array(
            &#39;mine&#39; =&gt; &#39;true&#39;,
        ));

        $htmlBody = &#39;&#39;;
        foreach ($channelsResponse[&#39;items&#39;] as $channel) {
            // Extract the unique playlist ID that identifies the list of videos
            // uploaded to the channel, and then call the playlistItems.list method
            // to retrieve that list.
            $uploadsListId = $channel[&#39;contentDetails&#39;][&#39;relatedPlaylists&#39;][&#39;uploads&#39;];

            $playlistItemsResponse = $youtube-&gt;playlistItems-&gt;listPlaylistItems(&#39;snippet&#39;, array(
                &#39;playlistId&#39; =&gt; $uploadsListId,
                &#39;maxResults&#39; =&gt; 50
            ));

            $htmlBody .= &quot;&lt;h3&gt;Videos in list $uploadsListId&lt;/h3&gt;&lt;ul&gt;&quot;;
            foreach ($playlistItemsResponse[&#39;items&#39;] as $playlistItem) {
                $htmlBody .= sprintf(&#39;&lt;li&gt;%s (%s)&lt;/li&gt;&#39;, $playlistItem[&#39;snippet&#39;][&#39;title&#39;],
                    $playlistItem[&#39;snippet&#39;][&#39;resourceId&#39;][&#39;videoId&#39;]);
            }
            $htmlBody .= &#39;&lt;/ul&gt;&#39;;
        }
    } catch (Google_ServiceException $e) {
        $htmlBody .= sprintf(&#39;&lt;p&gt;A service error occurred: &lt;code&gt;%s&lt;/code&gt;&lt;/p&gt;&#39;,
            htmlspecialchars($e-&gt;getMessage()));
    } catch (Google_Exception $e) {
        $htmlBody .= sprintf(&#39;&lt;p&gt;An client error occurred: &lt;code&gt;%s&lt;/code&gt;&lt;/p&gt;&#39;,
            htmlspecialchars($e-&gt;getMessage()));
    }

    $_SESSION[&#39;token&#39;] = $client-&gt;getAccessToken();
} else {
    $state = mt_rand();
    $client-&gt;setState($state);
    $_SESSION[&#39;state&#39;] = $state;

    $authUrl = $client-&gt;createAuthUrl();
    $htmlBody = &lt;&lt;&lt;END
  &lt;h3&gt;Authorization Required&lt;/h3&gt;
  &lt;p&gt;You need to &lt;a href=&quot;$authUrl&quot;&gt;authorise access&lt;/a&gt; before proceeding.&lt;p&gt;
END;
}
?&gt;

echo $htmlBody;

?&gt;

 

Now execute your newly created file. http://<YourDomain>/Youtube/Authenticate.php.
On this page click on Authenticate link to connect your youtube account. On Success you got an access token save your token in new file named the_key.txt.
{"access_token":"xxxxxxxxxxxx","token_type":"Bearer","expires_in":3600,"refresh_token":"xxxxxxxx","created":xxxxxxx}
Upload it on the server now on server we have below file structure
  • Google/
  • Authenticate.php (We created this file previously)
  • the_key.txt (This is very importatn file. For security reasons you need to place the_key.txt file in such a way that now one can able to access it, except your PHP code.)
  • YouTube_Upload_Test.mp4 (Video need to upload)
  • Upload.php (the code for this available below)
Now create a new File named Upload.php and use below code.
&lt;?php

$key = file_get_contents(&#39;the_key.txt&#39;);


require_once $_SERVER[&quot;DOCUMENT_ROOT&quot;].&quot;/Youtube/Google/Client.php&quot;;
require_once $_SERVER[&quot;DOCUMENT_ROOT&quot;].&quot;/Youtube/Google/Service/YouTube.php&quot;;

$application_name = &quot;Replace This&quot;;
$client_secret = &quot;Replace This&quot;;
$client_id = &quot;Replace This&quot;;
$scope = array(&quot;https://www.googleapis.com/auth/youtube.upload&quot;, &quot;https://www.googleapis.com/auth/youtube&quot;, &quot;https://www.googleapis.com/auth/youtubepartner&quot;);

$videoPath = &quot;YouTube_Upload_Test.mp4&quot;;
$videoTitle = &quot;Video Title&quot;;
$videoDescription = &quot;Video Description&quot;;
$videoCategory = &quot;22&quot;;
$videoTags = array(&quot;youtube&quot;, &quot;tutorial&quot;);


try{
    // Client init
    $client = new Google_Client();
    $client-&gt;setApplicationName($application_name);
    $client-&gt;setClientId($client_id);
    $client-&gt;setAccessType(&#39;offline&#39;);
    $client-&gt;setAccessToken($key);
    $client-&gt;setScopes($scope);
    $client-&gt;setClientSecret($client_secret);

    if ($client-&gt;getAccessToken()) {

        /**
         * Check to see if our access token has expired. If so, get a new one and save it to file for future use.
         */
        if($client-&gt;isAccessTokenExpired()) {
            $newToken = json_decode($client-&gt;getAccessToken());
            $client-&gt;refreshToken($newToken-&gt;refresh_token);
            file_put_contents(&#39;the_key.txt&#39;, $client-&gt;getAccessToken());
        }

        $youtube = new Google_Service_YouTube($client);



        // Create a snipet with title, description, tags and category id
        $snippet = new Google_Service_YouTube_VideoSnippet();
        $snippet-&gt;setTitle($videoTitle);
        $snippet-&gt;setDescription($videoDescription);
        $snippet-&gt;setCategoryId($videoCategory);
        $snippet-&gt;setTags($videoTags);

        // Create a video status with privacy status. Options are &quot;public&quot;, &quot;private&quot; and &quot;unlisted&quot;.
        $status = new Google_Service_YouTube_VideoStatus();
        $status-&gt;setPrivacyStatus(&#39;public&#39;);

        // Create a YouTube video with snippet and status
        $video = new Google_Service_YouTube_Video();
        $video-&gt;setSnippet($snippet);
        $video-&gt;setStatus($status);

        // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
        // for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
        $chunkSizeBytes = 1 * 1024 * 1024;

        // Setting the defer flag to true tells the client to return a request which can be called
        // with -&gt;execute(); instead of making the API call immediately.
        $client-&gt;setDefer(true);

        // Create a request for the API&#39;s videos.insert method to create and upload the video.
        $insertRequest = $youtube-&gt;videos-&gt;insert(&quot;status,snippet&quot;, $video);

        // Create a MediaFileUpload object for resumable uploads.
        $media = new Google_Http_MediaFileUpload(
            $client,
            $insertRequest,
            &#39;video/*&#39;,
            null,
            true,
            $chunkSizeBytes
        );
        $media-&gt;setFileSize(filesize($videoPath));


        // Read the media file and upload it chunk by chunk.
        $status = false;
        $handle = fopen($videoPath, &quot;rb&quot;);
        while (!$status &amp;&amp; !feof($handle)) {
            $chunk = fread($handle, $chunkSizeBytes);
            $status = $media-&gt;nextChunk($chunk);
        }

        fclose($handle);

        /**
         * Video has successfully been upload, now lets perform some cleanup functions for this video
         */
        if ($status-&gt;status[&#39;uploadStatus&#39;] == &#39;uploaded&#39;) {
            // Actions to perform for a successful upload
        }

        // If you want to make other calls after the file upload, set setDefer back to false
        $client-&gt;setDefer(true);

    } else{
        // @TODO Log error
        echo &#39;Problems creating the client&#39;;
    }

} catch(Google_Service_Exception $e) {
    print &quot;Caught Google service Exception &quot;.$e-&gt;getCode(). &quot; message is &quot;.$e-&gt;getMessage();
    print &quot;Stack trace is &quot;.$e-&gt;getTraceAsString();
}catch (Exception $e) {
    print &quot;Caught Google service Exception &quot;.$e-&gt;getCode(). &quot; message is &quot;.$e-&gt;getMessage();
    print &quot;Stack trace is &quot;.$e-&gt;getTraceAsString();
}

?&gt;

 

Finally visit http://<YourDomain>/Youtube/Upload.php to upload your video. Congratulation you created a PHP script to upload your videos on Youtube. 
Note this script is very basic and not recommended to use on production environment. You need to modify both the scripts based on your requirement and ensure only authenticated users are able to access the above scripts to avoid the misuse. 
0 Comments
Leave A Comment

Please login to post your valuable comments.

Join the newsletter

Get the latest vLemonn news first

share