I was able to get the upload working using the following code:

if($client->getAccessToken()) {
    $snippet = new Google_VideoSnippet();
    $snippet->setTitle("Test title");
    $snippet->setDescription("Test descrition");
    $snippet->setTags(array("tag1","tag2"));
    $snippet->setCategoryId("22");

    $status = new Google_VideoStatus();
    $status->privacyStatus = "private";

    $video = new Google_Video();
    $video->setSnippet($snippet);
    $video->setStatus($status);

    $error = true;
    $i = 0;

    try {
        $obj = $youTubeService->videos->insert("status,snippet", $video,
                                         array("data"=>file_get_contents("video.mp4"), 
                                        "mimeType" => "video/mp4"));
    } catch(Google_ServiceException $e) {
        print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br>";
        print "Stack trace is ".$e->getTraceAsString();
    }
}
Answer from jayendrap on Stack Overflow
Top answer
1 of 4
8

I was able to get the upload working using the following code:

if($client->getAccessToken()) {
    $snippet = new Google_VideoSnippet();
    $snippet->setTitle("Test title");
    $snippet->setDescription("Test descrition");
    $snippet->setTags(array("tag1","tag2"));
    $snippet->setCategoryId("22");

    $status = new Google_VideoStatus();
    $status->privacyStatus = "private";

    $video = new Google_Video();
    $video->setSnippet($snippet);
    $video->setStatus($status);

    $error = true;
    $i = 0;

    try {
        $obj = $youTubeService->videos->insert("status,snippet", $video,
                                         array("data"=>file_get_contents("video.mp4"), 
                                        "mimeType" => "video/mp4"));
    } catch(Google_ServiceException $e) {
        print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br>";
        print "Stack trace is ".$e->getTraceAsString();
    }
}
2 of 4
5

I realize this is old, but here's the answer off the documentation:

    // REPLACE this value with the path to the file you are uploading.
    $videoPath = "/path/to/file.mp4";

    $snippet = new Google_Service_YouTube_VideoSnippet();
    $snippet->setTitle("Test title");
    $snippet->setDescription("Test description");
    $snippet->setTags(array("tag1", "tag2"));

    // 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 = 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.
    $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);
๐ŸŒ
CodexWorld
codexworld.com โ€บ home โ€บ upload video to youtube using php
Upload Video to YouTube using PHP - CodexWorld
May 4, 2022 - YouTube Data API provides the easiest way to upload video to YouTube channel with PHP. You can upload videos from the website to YouTube channel using PHP.
Discussions

session - PHP Youtube API upload video code sample uploads twice - Stack Overflow
I am using the php code sample for uploading a video provided by youtube, which can be found here: https://developers.google.com/youtube/v3/code_samples/php#upload_a_video However, when the session More on stackoverflow.com
๐ŸŒ stackoverflow.com
PHP + Youtube API - how to allow user to upload videos to my own channel? - Stack Overflow
I am trying to build a web app that allows users to upload videos to my channel. So I think I must go for OAuth 2.0 for Server to Server Applications, just as it says it there: Typically, an More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 3, 2016
video - youtube api v3.0 Browser-based Uploading in php - Stack Overflow
i'm trying (php) to upload a video (browser based not storing video in my app want to upload straight to youtube). I cant find any docs on this. Eg like this https://developers.google.com/youtube... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 28, 2017
Upload a video in my YouTube channel using PHP api - Stack Overflow
I follow as explained youtube API https://developers.google.com/youtube/v3/code_samples/php#upload_a_video below is my code More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 3, 2016
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ t โ€บ php-youtube-api-upload-video โ€บ 608676
PHP youtube api upload video - The freeCodeCamp Forum
May 7, 2023 - i have all my auth and accounts setup properly. im having trouble uploading videos from an external source. the POST isnt sending data. also manually it gets stuck as pending on yt studio i have one page where i authenticate myself: require_once __DIR__ . '/vendor/autoload.php'; $client = new Google_Client(); $client->setApplicationName('testapp'); $client->setRedirectUri('http://localhost/ytapi.php'); $client->setScopes(['https://www.googleapis.com/auth/youtube']); $client->setAuthConfig('we...
๐ŸŒ
GitHub
github.com โ€บ youtube โ€บ api-samples โ€บ blob โ€บ master โ€บ php โ€บ resumable_upload.php
api-samples/php/resumable_upload.php at master youtube/api-samples ยท GitHub
// 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.
Author: youtube
๐ŸŒ
GitHub
github.com โ€บ ZiTAL โ€บ youtube-php-cli
GitHub - ZiTAL/youtube-php-cli: Youtube API for php to upload videos through console
When the token.json is created we never use the google page to get the token, the token can be refreshed through code -youtube_uploader.php-: // ... private function tokenRefresh() { if($this->client->isAccessTokenExpired()) { $newToken = $this->client->getAccessToken(); $this->client->refreshToken($newToken['refresh_token']); $newToken = $this->client->getAccessToken(); file_put_contents($this->token_file, json_encode($newToken, JSON_PRETTY_PRINT)); } } // ... This example uploads a example video to your youtube account in private mode, check it in: https://www.youtube.com/my_videos?o=U
Starred by 11 users
Forked by 7 users
Languages: PHP 100.0% | PHP 100.0%
๐ŸŒ
Artisans Web
artisansweb.net โ€บ home โ€บ how to use youtube api to upload video on youtube channel
How to use YouTube API to Upload Video on YouTube Channel - Artisans Web
July 24, 2023 - You will get client ID and client secret in the pop-up. Copy these details. We will need it in a moment. Uploading video using the YouTube API requires you to create an access token.
๐ŸŒ
Medium
medium.com โ€บ @hichamelaziz855 โ€บ upload-video-to-youtube-using-php-codexworld-ed2efc97c5e9
Upload Video to YouTube using PHP โ€” CodexWorld | by Hichamelaziz | Medium
May 17, 2022 - Upload file to the local server and insert video details in the database using PHP and MySQL. Store DB reference ID of the file in SESSION. Create OAuth URL using createAuthUrl() method of Google_Client class.
๐ŸŒ
Coders Opinion
codersopinion.com โ€บ blog โ€บ uploading-a-video-to-youtube-through-api-version-3-in-php
Uploading a video to youtube through api version 3 in PHP - Coders Opinion
May 23, 2013 - $_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_up
Find elsewhere
๐ŸŒ
DC Blog
dcblog.dev โ€บ how-to-upload-videos-to-youtube-with-php
How to upload videos to YouTube with PHP - David Carr's Blog
March 12, 2022 - For other response code see this reference: https://developers.google.com/youtube/2.0/reference#Response_codes_uploading_videos ยท <?php session_start(); require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path Zend_Loader::loadClass('Zend_Gdata_YouTube'); Zend_Loader::loadClass('Zend_Gdata_AuthSub'); function getAuthSubRequestUrl() { $next = 'http://dcblog.dev/demos/youtube-upload'; $scope = 'http://gdata.youtube.com'; $secure = false; $session = true; return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session); } //generate link if no session or token has been requested if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){ echo '<a href="' .
Top answer
1 of 2
6

You can use the following code to upload the file just after user has signin when user click a submit button with the path defined in a text input :

<?php
/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();

$response = "";

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'YOUR_CLIENTID';
$OAUTH2_CLIENT_SECRET = 'YOUR_CLIENT_SECRET';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');

$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);

$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// 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);
}
if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.

if ($client->getAccessToken()) {
  try {

    $videoPath = "";

    if (isset($_GET['videoPath'])){
    $videoPath = $_GET['videoPath'];
    }
    else if(isset($_SESSION['videoPath'])){
      $videoPath = $_SESSION['videoPath'];
    }

    if(isset($videoPath) && !isset($_GET['state']) && file_exists($videoPath)) {

      // 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("Test title");
      $snippet->setDescription("Test description");
      $snippet->setTags(array("tag1", "tag2"));

      // 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 = "private";

      // 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 = 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.
      $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);

      $response .= "<h3>Video Uploaded</h3><ul>";
      $response .= sprintf('<li>%s (%s)</li>',
          $status['snippet']['title'],
          $status['id']);

      $response .= '</ul>';

      $_SESSION['path'] = "";
  }
  else{
    $response = "no path was specified or file doesn't exist";
    file_put_contents('php://stderr', print_r("no path was specified or file doesn't exist", TRUE));
  }

  } catch (Google_Service_Exception $e) {
    $response = htmlspecialchars($e->getMessage());
  } catch (Google_Exception $e) {
    $response = htmlspecialchars($e->getMessage());
  }
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
} else {

  if(isset($_GET['videoPath'])){

    $_SESSION["videoPath"] = $_GET['videoPath'];

    // If the user hasn't authorized the app, initiate the OAuth flow
    $state = mt_rand();
    $client->setState($state);
    $_SESSION['state'] = $state;
    $authUrl = $client->createAuthUrl();
    header('Location: ' . $authUrl);
  }
}
?>

<!doctype html>
<html>
<head>
 <title>Upload Video</title>
</head>
<body>
   <div>
        <form id="form" action="resumable_upload.php"">

          <label>Enter the path to the video to upload
           :
                <input id="video-path" name="videoPath" value='/path/to/video' type="text" />
          </label>
          <input name="action" type="submit" value="Upload video" />
        </form>
        <div id="playlist-container">
          <?php echo $response ?>
        </div>
    </div>
</body>
</html>

But if the page gets refreshed or if the user clicks the button by mistake one more time, it will re-upload the video. Check this post to deal with the duplicated video issue

2 of 2
-1

I know this question is old but this is a issue I was struggling with for a while.

In my situation, I had a form that needed to pass values to my upload script, and if a user wasn't signed in then the post values would get lost during the sign in process. So I came up with a way using session variables.

First towards the start of my script I set a variable to count the 'page' views -

// set the session views
if (!isset($_SESSION['views'])) {
    $_SESSION['views'] = 0;
}

// every view increments
$_SESSION['views'] = $_SESSION['views'] + 1;

Then I stored session variables.

        // If the user hasn't authorized the app, initiate the OAuth flow
        $state = mt_rand();
        $client->setState($state);
        $_SESSION['state'] = $state;

        $authorID   = $_POST['a_id'];
        $videoTitle = $_POST['ytu_title'];

        // Set session variables
        $vidID  = $_POST['vid_id'];
        $_SESSION["author"] = $_POST['a_id'];
        $_SESSION["title"]  = $_POST['ytu_title'];
        $_SESSION["video"] = $vidID;

Then I put an if statement to check the views before uploading -

// if its on the third view or more
if ($_SESSION['views'] >= 3) {
    // 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($_SESSION["title"]);
                $snippet->setDescription("Youtube Video.");
                $snippet->setTags(array(
                    "test",
                    "test 2"
                ));
    // and rest of the upload part from upload php script
    // etc etc

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

    } // closing if statement

I was finally able to fix my issue with the if statement before uploading.

๐ŸŒ
Domsammut
domsammut.com โ€บ code โ€บ php-server-side-youtube-v3-oauth-api-video-upload-guide
PHP server-side YouTube V3 OAuth API video upload guide / Dom Sammut
A guide on how to setup a server-side YouTube upload script using the V3 OAuth API in PHP, including how to generate and store a refresh token using PHP.
Top answer
1 of 2
4

I think I found the answer from this article.

Steps:

Step 1. Create a token.php (make sure set it to 777). Place the code example from Google - https://developers.google.com/youtube/v3/code_samples/php#upload_a_video - with a little of this modification as follow:

Change:

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

To:

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);

  // @ref: http://www.whitewareweb.com/php-youtube-video-upload-google-api-oauth-2-0-v3/
  echo "Access Token: " . $_SESSION['token'];
}

Step 2. Run token.php on your browser. Grant the access. Then you get a json output below:

{
  "access_token": "xxxxt7YvjObwYx3DG4NRmfjiQ",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "xxxxq5hzQTUapZ7zyRIHP7X_G8",
  "created": 1466238624
}

Save it as token.txt

Step 3. Create upload.php with the same example code from Google - with the following modification:

One. Include token.txt file in the beginning of your upload.php:

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

Then pass $key into new Google_Client():

$OAUTH2_CLIENT_ID = 'xxxx.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'xxxx';

// Client init
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken($key);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);

Two. Add this code in the try catch section before $youtube = new Google_Service_YouTube($client);:

    /**
     * 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());
        $client->refreshToken($newToken->refresh_token);
        file_put_contents('token.txt', $client->getAccessToken());
    }

Step 4. Run upload.php that's it.

You can get the entire code from that article.

2 of 2
-1

I know this sounds pretty weird, but I had the same issue the other day. I was trying different things... Try to change the YouTube category ID...

Try to change it to 1, took me hours of troubleshooting this to finally find that a lot of the categories do not work in the YouTube PHP SDK.

If that works, might want to make an API call to YouTube and get a list of all Category ID's, and try them all individually until you find the ones that do work... Documentation on how to do that is here: https://developers.google.com/youtube/v3/docs/videoCategories/list

This is assuming that you have all of your OAuth tokens correct.

๐ŸŒ
YouTube
youtube.com โ€บ watch
Upload Video to YouTube using PHP - YouTube
Read Tutorial and Download source code from CodexWorld.com - http://www.codexworld.com/upload-video-to-youtube-using-php/Upload video from website to YouTube...
Published: October 10, 2017
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 38742383 โ€บ upload-a-video-in-my-youtube-channel-using-php-api
Upload a video in my YouTube channel using PHP api - Stack Overflow
August 3, 2016 - $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.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Upload Video on YouTube using YouTube API in Laravel ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
Published: April 26, 2020
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 13954601 โ€บ uploading-file-with-youtube-api-v3-and-php
Uploading file with Youtube API v3 and PHP - Stack Overflow
December 19, 2012 - public function upload(){ if(isset($_FILES['userfile'])) { $snippet = new Google_VideoSnippet(); $snippet->setTitle("Test v3"); $snippet->setDescription("First upload using api v3"); $snippet->setTags(array("api","v3")); $video = new Google_Video(); $video->setSnippet($snippet); $response = $this->googleapi->youtube->videos->insert( "status,snippet", $video, array('data' => $_FILES['userfile']['tmp_name']) ); var_dump($response); }else{ $this->load->view('youtube'); } } The response is empty, because io/Google_REST.php throws
๐ŸŒ
YouTube
youtube.com โ€บ watch
Upload Video On YouTube Channel Using YouTube API - YouTube
Everybody knows about YouTube. YouTube is the number one video-sharing website in the world. We can use YouTube to host our videos. This saves us a lot of se...
Published: April 19, 2020