youtube

Uploading a video to youtube through api version 3 in PHP

I’ve been trying to get the API from google youtube to work so I can upload video’s to it from my web application. It took me extremely long to figure out how the API worked because of lack of documentation at this moment. That is why I’m writing a blog post about it so people will hopefully have less trouble with it.

Downloading the Google PHP Library

First you need to get the Google PHP API Libary so not the Zend libary. As you can see that libary also has an example. Parts of that example we will use to handle the authentication for us.

Registering your Google API Client and Developer Keys

Now you need to register your client and developer keys. Registering your Client Key can be done at the Google Api Console. Here you can register your client key at “Client ID for web applications” and your developer key at “Simple API Access”. More information can be found at the Google PHP Client OAuth2 Docs

The PHP Code used to Upload a Video to Youtube

The following code is partly from google and Partly written by me trying to figgure out for the google version 3 api is working.

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_YouTubeService.php';

// Set your cached access token. Remember to replace $_SESSION with a real database or memcached.
session_start();

// Connect to the Account you want to upload the video to (Note: When Remembering your access code you only need to do this once)
$client = new Google_Client();
$client->setApplicationName('Youtube PHP Starter Application');
$client->setClientId('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setDeveloperKey('insert_your_simple_api_key');

// Load the Youtube Service Library
$youtube = new Google_YouTubeService($client);

// Authenticate the user when he comes back with the access code
if (isset($_GET['code']))
{
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

// Check if the Token is set in the Session. If so set it to the client
if (isset($_SESSION['token']))
{
    $client->setAccessToken($_SESSION['token']);
}

// Check if the client has an access Token elke Give him a login Link
if ($client->getAccessToken())
{
    // Upload the youtube Video
    try
    {
        $path_to_video_to_upload = '/set/the/direct/path/to/your/video.avi';

        // Get the Mimetype of your video
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($finfo, $path_to_video_to_upload);

        // Build the Needed Video Information
        $snippet = new Google_VideoSnippet();
        $snippet->setTitle('Title Of Video');
        $snippet->setDescription('Description Of Video');
        $snippet->setTags(array('Tag 1', 'Tag 2'));
        $snippet->setCategoryId(22);

        // Build the Needed video Status
        $status = new Google_VideoStatus();
        $status->setPrivacyStatus('private'); // or public, unlisted

        // Set the Video Info and Status in the Main Tag
        $video = new Google_Video();
        $video->setSnippet($snippet);
        $video->setStatus($status);

        // Send the video to the Google Youtube API
        $created_file = $youtube->videos->insert('snippet,status', $video, array(
            'data' => file_get_contents($path_to_video_to_upload),
            'mimeType' => $mime_type,
        ));

        // Get the information of the uploaded video
        print_r($createdFile);
    }
    catch (Exception $ex)
    {
        echo $ex;
    }

    // We're not done yet. Remember to update the cached access token.
    // Remember to replace $_SESSION with a real database or memcached.
    $_SESSION['token'] = $client->getAccessToken();
}
else
{
    $authUrl = $client->createAuthUrl();
    print "<a href='$authUrl'>Connect Me!</a>";
}

That’s it. I hope you have enough information to get your youtube upload with API version 3 working like it should. If you have questions of some information is lacking feel free to request it in the comments section.

A list of the Category Id’s you can use

"id": "1",
"title": "Film & Animation"

"id": "2",
"title": "Autos & Vehicles"

"id": "10",
"title": "Music"

"id": "15",
"title": "Pets & Animals"

"id": "17",
"title": "Sports"

"id": "18",
"title": "Short Movies"

"id": "19",
"title": "Travel & Events"

"id": "20",
"title": "Gaming"

"id": "21",
"title": "Videoblogging"

"id": "22",
"title": "People & Blogs"

"id": "23",
"title": "Comedy"

"id": "24",
"title": "Entertainment"

"id": "25",
"title": "News & Politics"

"id": "26",
"title": "Howto & Style"

"id": "27",
"title": "Education"

"id": "28",
"title": "Science & Technology"

"id": "29",
"title": "Nonprofits & Activism"

// Start Movie Tags
"id": "30",
"title": "Movies"

"id": "31",
"title": "Anime/Animation"

"id": "32",
"title": "Action/Adventure"

"id": "33",
"title": "Classics"

"id": "34",
"title": "Comedy"

"id": "35",
"title": "Documentary"

"id": "36",
"title": "Drama"

"id": "37",
"title": "Family"

"id": "38",
"title": "Foreign"

"id": "39",
"title": "Horror"

"id": "40",
"title": "Sci-Fi/Fantasy"

"id": "41",
"title": "Thriller"

"id": "42",
"title": "Shorts"

"id": "43",
"title": "Shows"

"id": "44",
"title": "Trailers"
// End Movie Tags

Author: Robert Jan de Dreu

21 thoughts on “Uploading a video to youtube through api version 3 in PHP”

  1. Hi Robert

    i use your code but Give this error

    Fatal error: Uncaught exception ‘Google_AuthException’ with message ‘Could not json decode the token’ in /var/websites/dev0_space_com/webroot/you/google-api-php-client/src/auth/Google_OAuth2.php:154 Stack trace: #0 /var/websites/dev0_space_com/webroot/you/google-api-php-client/src/Google_Client.php(174): Google_OAuth2->setAccessToken(‘ya29.AHES6ZRU6s…’) #1 /var/websites/dev0_space_com/webroot/you/youtuberefreshtokenv3.php(94): Google_Client->setAccessToken(‘ya29.AHES6ZRU6s…’) #2 {main} thrown in /var/websites/dev0_space_com/webroot/you/google-api-php-client/src/auth/Google_OAuth2.php on line 154

    plz help

  2. @AShok: It seems that your access code is not returned as a json code like it should. Normally the access code is a json string with multiple values.

  3. Hi Robert

    i solved this problem but i need a permanent token or anything
    for multiple video upload.

    any idea

    i get refresh token for new token but it is not working this library.
    any other idea for this problem.

    through curl or anythig

  4. @AShok: You need to store it and renew it in a persistent storage like a database or memcached. Since you need to refresh the token regulary with the refresh token.

  5. Hi Robert

    i use refresh token for new access token through CURL and i get also new access token but this access token not support in this library
    like this error:

    Fatal error: Uncaught exception ‘Google_AuthException’ with message ‘Could not json decode the token’

  6. Hi Robert
    I found this function for refresh token But not return anything
    how to use this function for new access token for uploading video
    one video is uploading for one access Token

    /**
    * Fetches a fresh OAuth 2.0 access token with the given refresh token.
    * @param string $refreshToken
    * @return void
    */
    public function refreshToken($refreshToken) {
    self::$auth->refreshToken($refreshToken);
    }

  7. How do we get infos for
    $client->setApplicationName(‘Youtube PHP Starter Application’);
    $client->setClientId(‘insert_your_oauth2_client_id’);
    $client->setClientSecret(‘insert_your_oauth2_client_secret’);
    $client->setRedirectUri(‘insert_your_oauth2_redirect_uri’);
    $client->setDeveloperKey(‘insert_your_simple_api_key’);

  8. Sorry Robert.
    I’m trying updating the video info and I have no idea. I only know that i have to use this method:

    $created_file = $youtube->videos->update(‘snippet’, $video, array(
    ));

    But I dont know how to pass the id video parameter.
    Could you help me, please??

  9. @Blaaze Sadly I never tried to do so. Could you please explain more about the problem that is occuring for you?

    @manihs What do you mean exactly?

  10. Hello Robert. First, I will like to say a big thank you for the uploading Video to Youtube PHP Script. It works wonder.

    However, I want to allow anyone register on my site, to upload their videos on my own youtube user channel not user’ Youtube Channel.

    Please, I do I ensure that user’s don’t have to be redirected to a Google Login page when clicked on the link: Login to YouTube API!

    Basically, the users are already in a secure area of my website and when the click a link, they should be able to upload videos to my own youtube channel.

    Best Regards

  11. Hi Robert

    i am using your code but Give this following error :

    exception ‘Google_ServiceException’ with message ‘Error calling POST https://www.googleapis.com/upload/youtube/v3/videos?part=snippet%2Cstatus&uploadType=multipart: (403) Access Not Configured. Please use Google Developers Console to activate the API for your project.’ in /opt/lampp/htdocs/youtube/google-api-php-client/src/io/Google_REST.php:66 Stack trace: #0 /opt/lampp/htdocs/youtube/google-api-php-client/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 /opt/lampp/htdocs/youtube/google-api-php-client/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 /opt/lampp/htdocs/youtube/google-api-php-client/src/contrib/Google_YouTubeService.php(887): Google_ServiceResource->__call(‘insert’, Array) #3 /opt/lampp/htdocs/youtube/google-api-php-client/src/upload.php(66): Google_VideosServiceResource->insert(‘snippet,status’, Object(Google_Video), Array) #4 {main}

    Any help… :-)

  12. Thanks for the script. Pretty good job! When I run it without being connected, I got: “This app would like to Connect to your youtube account”. I click accept which directs me to an error page saying my browser can’t connect to the server at the address localhost. I use WAMP. Should I configure something? I am a bit lost. Thanks

  13. Hi,
    Thanks for the code should save me lots of time :) However the 2 includes
    src/Google_Client.php
    src/contrib/Google_YouTubeService.php
    are not in the github api download. Which exact version is the code written to work with, please?
    Rob

  14. Quick look suggests that the functions are all in src/Google/Service.php & src/Google/Client.php. Mybe a couple of functions to rename…

    Rob

Leave a Reply