Found this useful? Love this post

PHP server-side YouTube V3 OAuth API video upload guide

Dec 2014 – Please note this post is based on the 1.0.5 version of the API. If you are using the latest version you’ll need to update file paths as the file/folder structure has changed significantly.

Many bothans died to bring you this information. And when I say bothans, I refer of course to brain cells that have died as result of me smashing my head against the YouTube api.

To make this work, you’ll need to create a dummy web application that can capture the refresh token generated when you authorise your app. You can read a detailed explanation of what we’ll be doing and how the OAuth process works here.

This implementation has no requirements for any PHP frameworks (such as Zend). It is a barebones implementation based off the documentation for the YouTube V3 API utilising the Google PHP API client.

Creating your project

  1. You’ll need to head over to and create a new project.
  2. Then go and enable the YouTube Data API – (Your Project > APIS & AUTH > APIs)
  3. We’ll now need to create some credentials. Go to Your Project > APIS & AUTH > Credentials
  4. Click “Create new Client ID” and then under “Application Type” select “Web Application”.
  5. You’ll then need to enter your JavaScript origin and authorised redirect URI. I just set this to localhost, but you can set it to where ever you want.
  6. We’ve now created our client ID, we just need to fill in the Consent Screen. We can do this by navigating to Your Project > APIS & AUTH > Consent Screen. Once you’re on this page, ensure you fill out all the required fields (Email Address and Product Name).
  7. Hurray, we’ve created our project.

Getting your refresh token

I used the following PHP script as my dummy application to generate the OAuth token.

This script utilises Google APIs Client Library for PHP. You’ll need to download and install it a directory that can be read using the below script.


// Call set_include_path() as needed to point to your client library.
set_include_path($_SERVER['DOCUMENT_ROOT'] . '/directory/to/google/api/');
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ }}>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <>
 * Please ensure that you have enabled the YouTube Data API for your project.
$REDIRECT = 'http://localhost/oauth2callback.php';

$client = new Google_Client();

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

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

    $_SESSION['token'] = $client->getAccessToken();


if (isset($_SESSION['token'])) {
    echo '<code>' . $_SESSION['token'] . '</code>';

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

        $htmlBody = '';
        foreach ($channelsResponse['items'] 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['contentDetails']['relatedPlaylists']['uploads'];

            $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
                'playlistId' => $uploadsListId,
                'maxResults' => 50

            $htmlBody .= "<h3>Videos in list $uploadsListId</h3><ul>";
            foreach ($playlistItemsResponse['items'] as $playlistItem) {
                $htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'],
            $htmlBody .= '</ul>';
    } catch (Google_ServiceException $e) {
        $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
    } catch (Google_Exception $e) {
        $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',

    $_SESSION['token'] = $client->getAccessToken();
} else {
    $state = mt_rand();
    $_SESSION['state'] = $state;

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

<!doctype html>
    <title>My Uploads</title>
<?php echo $htmlBody?>

Once you’ve got the script above and the Google Client Library API in place, load the script in your browser. You should be prompted to Authorise access before you can continue. Once you click on this link you should be taken through the steps to authorise your currently logged in Google account to access your new application.

Once it’s all done you should be redirected back to the localhost page, except now you will see a JSON string along the top of the page. Save this string somewhere for use later on. You might also notice if you’ve already uploaded videos to YouTube, a list of your videos on the page – just to confirm the access token works!

Saving your credentials

Now that you’ve received your refresh tokens create a text file called “the_key.txt” with the following information you’ve just received, it should look something similar to the format below:

{"access_token":"XXXXXXXXX","token_type":"Bearer", "expires_in":3600, "refresh_token":"XXXXXXX", "created":000000}

I suggest you write your refresh token down somewhere for safe keeping.


Creating the upload script

The script below is a very basic implementation. It requires the following file structure:

  • Google/
  • upload.php (the script below)
  • the_key.txt (the file we created in the previous section)
  • tutorial.mp4 (the video to upload)

The script will automatically update your “the_key.txt” file if your access_token is out of date.

Set the include path to ensure the Google API works correctly (line 3).

Replace the following variables with your own information:

  • $application_name
  • $client_secrect
  • $client_id
  • $videoPath
  • $videoTitle
  • $videoDescription
  • $videoCategory
  • $videoTags


$key = file_get_contents('the_key.txt');

set_include_path($_SERVER['DOCUMENT_ROOT'] . '/path-to-your-director/');
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

$application_name = 'XXXXXX'; 
$client_secret = 'XXXXXXX';
$client_id = '';
$scope = array('', '', '');
$videoPath = "tutorial.mp4";
$videoTitle = "A tutorial video";
$videoDescription = "A video tutorial on how to upload to YouTube";
$videoCategory = "22";
$videoTags = array("youtube", "tutorial");

	// Client init
	$client = new Google_Client();

	if ($client->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->isAccessTokenExpired()) {
			$newToken = json_decode($client->getAccessToken());
			file_put_contents('the_key.txt', $client->getAccessToken());

		$youtube = new Google_Service_YouTube($client);

		// Create a snipet with title, description, tags and category id
		$snippet = new Google_Service_YouTube_VideoSnippet();

		// Create a video status with privacy status. Options are "public", "private" and "unlisted".
		$status = new Google_Service_YouTube_VideoStatus();

		// Create a YouTube video with snippet and status
		$video = new Google_Service_YouTube_Video();

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


		 * Video has successfully been upload, now lets perform some cleanup functions for this video
		if ($status->status['uploadStatus'] == 'uploaded') {
			// Actions to perform for a successful upload
			// $uploaded_video_id = $status['id'];

		// If you want to make other calls after the file upload, set setDefer back to false

	} else{
		// @TODO Log error
		echo 'Problems creating the client';

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


As you can see, the script is very primitive, among other things, this script should not be located in a publicly accessible directory due to the obvious abuse that could occur. In my situation, I created a queue of files to upload and setup a cron to execute the script once an hour that would then check a directory for any files of a certain type (mp4) and then loop through and upload to YouTube. The method I described hasn’t been tested on files more than 10 x 400mb in size so I’m not sure what the impacts would be on your server for more files / larger sizes etc.

Hopefully that’s enough to get your started, if you have any questions feel free to ask :)


You'll only get 1 email per month containing new posts (I hate spam as much as you!). You can opt out at anytime.


Leave a Reply

Your email address will not be published. Required fields are marked *

Preview Comment


  1. 1wayrocker


    My var_dump($client->getAccessToken()); looks like this:

    array(6) { [“access_token”]=> string(131) “ya29.XXXXXXXXX” [“expires_in”]=> int(3600) [“scope”]=> string(47) “” [“token_type”]=> string(6) “Bearer” [“created”]=> int(1562173329) [“refresh_token”]=> string(45) “1/XXXXXXXXX” }

    but when it uses file_put_contents(‘the_key.txt’, $client->getAccessToken()); to put the array into the txt file it actually writes all values as 1 whole string. Like this:




    man, you awesome, thx!!!

  3. Bastien


    Hi Dom,

    Thank you for this post.
    Do you know if your code / logic is still possible with the V3 API if we wish to upload a video ?

    What “localhost” redirect URL you’ve decided to put when you’re in a server ?
    Thank you,

    • Dom Sammut

      Dom Sammut

      Hey Bastien,

      I haven’t tested with the latest release of the V3 API but the core principals should be same considering they’re still using OAuth. You might just need to update some of the Google API methods to reflect any new changes.

      In regards to the localhost URL, it needs to be something that will resolve on your computer / server of execution. You shouldn’t need the first half of the script after you’ve attained the refresh token and saved it to file.


      • Bastien


        Hi Dom

        Thank you for your quick response.
        Regarding your 2nd point, could you please tell me a bit more, or some example on it ? I’m bit confuse on it.

        Thank you again

        • Dom Sammut

          Dom Sammut

          Hey Bastien,

          The first part of the tutorial Getting your refresh token is what you’ll need to run once to get your refresh token that can be used in all subsequent requests to attain an access token. The tutorial outlines this pretty clearly in terms of what you need to do. Have you completed this step?


  4. parag


    Hi Dom,

    I have set-up a cron for regererate the token in every 30 min, but after couple of hours the file has no value (I’m only saving the refresh token in my file) what could be the issue. that the refresh token is return blank.

    I have now used snippet from your article for refresh token

    • Dom Sammut

      Dom Sammut

      Hey Parag,

      Are you logging the requests? What status code do you get when you’re attempting to refresh the token?


      • Parag


        I was uploading the file while uploading the video to YouTube and at that time the token is not refreshed, I have added the condition while writing the file. I’m pretty sure that issue is resolved, the file is not blank now.
        And albe to upload the multiple video one after anather.

        Also, I only use the refresh_token to save in the file, is that a good practice?.


        • Dom Sammut

          Dom Sammut

          Hey Parag,

          Correct, you’ll need to perform the token refresh (and ensure it is successful) before any other API actions are done.

          In regards to good practice, without knowing the circumstances of your environment it’s hard to know what’s best. In saying that, what you’ve suggested seems perfectly reasonable.


  5. Emmanuel


    I’m getting this error: “An client error occurred: ‘The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved” when I execute the second script (‘upload.php’).

    I think that I have an error in the line: set_include_path($_SERVER[‘DOCUMENT_ROOT’ . ‘google-api-php’]); because I’m not getting a new token.

    Thanks for the post and the help.

    • Dom Sammut

      Dom Sammut

      Hey Emmanuel,

      Can you confirm that you have a refresh token text file generated from the first script?


  6. Tihomir


    Hi Dom, friends,

    I use this guide in last 2 yeas with no problems. Now i build new instance and have problem with refresh token.

    Caught Google service Exception 400 message is Error refreshing the OAuth2 token, message: ‘{
    “error” : “invalid_request”,
    “error_description” : “Missing required parameter: refresh_token”

    Any working solution ?

  7. Marcelo


    Hi Dom, thanks for the post.

    Do you know if is it possible to upload the video, directly to Youtube, instead of having it locally ?
    Example: User uploads a video using my server, which uses the API to send it to Youtube.


    • Dom Sammut

      Dom Sammut

      Hey Marcelo,

      Yes this is possible, this post outlines how to implement a server-side upload like your example scenario.


  8. Tran Binh

    Tran Binh

    i converted it to a function.
    it working fine in session time (one hour)
    But, after one hour, it’s cant be refresh token, error:

    Caught Google service Exception 400 message is Error refreshing the OAuth2 token, message: ‘{
    “error” : “invalid_request”,
    “error_description” : “Could not determine client ID from request.”
    }’Stack trace is #0 C:\AppServ\www\yt\Google\Auth\OAuth2.php(272): Google_Auth_OAuth2->refreshTokenRequest(Array)
    #1 C:\AppServ\www\yt\Google\Client.php(421): Google_Auth_OAuth2->refreshToken(‘1/cIxhHOXDN6hVL…’)
    #2 C:\AppServ\www\yt\testupload.php(36): Google_Client->refreshToken(‘1/cIxhHOXDN6hVL…’)
    #3 C:\AppServ\www\yt\testupload.php(127): uploadYoutube(‘token/DMGG0c24e…’, ‘file.mp4’, ‘test title’, ‘description her…’, ’22’, Array)
    #4 {main}

    Can you help me..! Please

  9. Javier


    Hi Dom

    I have the following error trying to get the token on your first script:

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

    I read all comments and try everything but I still didn’t solve it.
    Can you please tell me what is wrong?

    My code is the same than you only replacing ID client, secret, redirect and app name.


  10. Dennis


    Hello. Thanx for the tutorial. I’ve made it as well.
    But my goal is a use of multiple accounts since they’ve limited Uploads count per day.
    So I wonder how to make it done without prompting each time new credentials on the consent screen?

    • Dom Sammut

      Dom Sammut

      Hey Dennis,

      You’d either need to grant access to all the different YouTube accounts to a single account or manually go through and store a refresh token for each account you’re looking to upload to. Not ideal, but not much else you can do at this point.


  11. Developer


    How is one able to specify $videopath to a html file input in your script?

  12. Developer


    Does this allow users to upload videos to the owner of the application’s youtube channel? If not how would you do this?

    • Dom Sammut

      Dom Sammut

      Yes it does.

  13. Den Zubr

    Den Zubr

    Good day, Dom. Your post was very useful to me, but I have a question: did you ever stack a problem with PHP upload photo to Instagram the same way, that you here discribed.

    • Dom Sammut

      Dom Sammut

      Hey Den,

      At this point in time Instagram doesn’t not have API support for creating content / posts.


  14. MikeW


    When I tried the code, it worked but it did not return any token though. It only printed a word “array” and followed my video list. The response url has state=xxxx&code=xxxx# with the # sign at the end. I think somehow the token got dropped. Where do you see them? This is happening to me for facebook php code too. a # sign in there so the server don’t see token response.

    • Rich


      I’m having the same issue. Did you ever get it figured out?