如何使用 Google API PHP 客户端库和 Youtube API V3 将视频上传到 YouTube?

2024-01-21

尝试简单地使用上传视频Google API PHP 客户端(最新版本 1.1.6) https://github.com/google/google-api-php-client/releases, but Youtube API V3 中的代码 https://developers.google.com/youtube/v3/code_samples/php#upload_a_video不工作并给出 500 内部服务器错误。

当我没有使用任何前沿测试版时,下面的代码有什么问题,我刚刚屏蔽了下面的 3 个参数,否则它会被复制形式Youtube API V3 https://developers.google.com/youtube/v3/code_samples/php#upload_a_video.

  require_once 'google-api-php-client/src/Google/Client.php';
  require_once 'google-api-php-client/src/Google/Service/YouTube.php';

  session_start();

  $OAUTH2_CLIENT_ID = 'CHANGE1-0osfh0p5h80o9ol2uqtsjq5i7r1jun.apps.googleusercontent.com';
  $OAUTH2_CLIENT_SECRET = 'CHANGE2azMpt__VdSt9';

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

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

    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    header('Location: ' . $redirect);
  }

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

  // Check to ensure that the access token was successfully acquired.
  if ($client->getAccessToken()) {
    try{
      // REPLACE this value with the path to the file you are uploading.
      $videoPath = "/CHANGE3/videos/test.mp4";

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


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

      $htmlBody .= '</ul>';

    } catch (Google_Service_Exception $e) {
      $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
      $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
          htmlspecialchars($e->getMessage()));
    }

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

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

发生服务错误: Error calling PUT https://www.googleapis.com/upload/youtube/v3/videos?part=status%2Csnippet&uploadType=resumable&upload_id=AEnB2UpXd4UQ0dt-v2_8YLzDp4KAywZQUIgUEm3Lxyv7nV_ZLAHghu6RiNE0e82xMMGx9ztQvTdYGFwvSNP5yJiOdffS0CuG-Q: (400) Failed to parse Content-Range header.

不要将其标记为与下面非常旧和已弃用的问题重复的问题,因为您可以看到其他问题甚至在其代码中包含最新版本中不存在的文件谷歌 API PHP 客户端 https://github.com/google/google-api-php-client库或指已失效的 Google 代码项目。类似的过时问题1 https://stackoverflow.com/questions/22042509/is-there-a-way-to-upload-videos-to-youtube-using-php, 2 https://stackoverflow.com/questions/9786140/upload-video-into-youtube-channel-through-php-script, 3 https://stackoverflow.com/questions/13177266/upload-video-to-youtube-using-php-client-library-v3, 4 https://stackoverflow.com/questions/14236502/upload-video-to-youtube-using-youtube-api-v3-and-php, 5 https://stackoverflow.com/questions/20189688/uploading-video-to-youtube-using-youtube-data-api-v3-and-google-api-client-php


奇怪的是,代码中的一个很小的调整就解决了这个问题。

而不仅仅是$videoPath = "/path/to/file.mp4";使用 DOCUMENT_ROOT 解决了该问题。除此之外,文档代码是完美的。

$videoPath = $_SERVER["DOCUMENT_ROOT"] . "/mapapp/videos/test.mp4";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Google API PHP 客户端库和 Youtube API V3 将视频上传到 YouTube? 的相关文章

  • WordPress 中的 add_action 函数

    嗯 我正在学习创建一个 WordPress 插件 我下载了一个并阅读了代码 然后我看到了这个 我假设 foo 是它将添加操作的标签 但是 array 到底是做什么的呢 add action foo array foo1 foo2 我在看ht
  • ORDER BY 字段内的 MySQL 子查询。 (没有内连接)

    有很多与此相关的问题 但都具有使用内部联接的相同答案 这 我认为 在这里是不可能的 如果我错了请告诉我 我现在正在做的是调用两个不同的 mysql 查询来获取结果 它工作完美 db gt query SELECT FROM meta WHE
  • PHP MySql 百分比

    我的问题是关于百分比 我不是专家 所以我会尽力以更好的方式进行解释 我的 mysql 服务器中有一个表 假设有 700 条记录 如下所示 Name country language Birth Lucy UK EN 1980 Mari Ca
  • 如何从 Laravel 中的表中选择所有列名称?

    我试图从表中获取所有列名Teller 功能 public function getTableColumns tables return DB select DB raw SELECT COLUMN NAME DATA TYPE COLUMN
  • 简单的 PHP 条件帮助: if($Var1 = in list($List) and $Cond2) - 这可能吗?

    这是一个可能的功能吗 我需要检查一个变量是否存在于我需要检查的变量列表中 并且 cond2 是否为 true 例如 if row name 1 2 3 Cond2 doThis 它对我不起作用 我在复制粘贴中更改的只是我的列表和变量名称 i
  • Laravel 从 5.6 升级到 Laravel 6

    我有一个项目https github com javedbaloch4 Laravel Booking https github com javedbaloch4 Laravel Booking发展于Laravel 5 6现在我想将其升级到
  • 通过 Ajax 加载内容时,WORDPRESS 音频播放器未加载,MediaElement.js 未应用

    我正在创建一个 WordPress 主题 当我使用 ajax 加载内容时 它不会将 MediaElements js 应用于我的音频播放器 因此不会显示音频 我认为这是因为 MediaElement js 加载了 wp footer 并且此
  • 单词之间没有空格的语言(例如亚洲语言)中的断词?

    我想让 MySQL 全文搜索适用于日语和中文文本以及任何其他语言 问题在于这些语言以及可能其他语言通常在单词之间没有空格 当您必须键入与文本中相同的句子时 搜索没有用 我不能只在每个字符之间添加空格 因为英语也必须有效 我想用 PHP 或
  • 检查 PHP 中“@”字符后面的单词

    我现在正在制作一个新闻和评论系统 但是我已经在一个部分上停留了一段时间了 我希望用户能够在 Twitter 上引用其他玩家的风格 例如 用户名 该脚本看起来像这样 不是真正的 PHP 只是想象脚本 3 string I loved the
  • Apache 访问 Linux 中的 NTFS 链接文件夹

    在 Debian jessie 中使用 Apache2 PHP 当我想在 Apache 的文档文件夹 var www 中创建一个新的小节时 我只需创建一个指向我的 php 文件所在的外部文件夹的链接 然后只需更改该文件夹的所有者和权限文件夹
  • PHP严格标准:声明应该兼容

    我有以下类层次结构 class O Base class O extends O Base abstract class A Abstract public function save O Base obj class A extends
  • 扩展蓝图类?

    我想覆盖timestamps 函数中发现Blueprint班级 我怎样才能做到这一点 e g public function up Schema create users function Blueprint table table gt
  • 蛋糕控制台 2.2.1:烘焙错误

    运行 MAMP 的 OSX 机器 CakePHP 2 2 1 已正确安装和配置 这意味着当我浏览到 Index php 文件时 所有绿色条都显示出来 我已经完成了博客教程 并且正在开发我的第二个应用程序 其中脚手架已启动并运行 现在我第一次
  • 是否可以使用 PHP 重定向发送 POST 数据?

    更新 这不是重复的如何使用 PHP 发送 POST 请求 https stackoverflow com questions 5647461 how do i send a post request with php 那里的解决方案对我不起
  • 从 smarty 访问 PHP 文件的变量(本地或全局)

    我有一个 php 文件 其中包含一些本地和全局变量 例如 foo 从此文件中调用 smarty 对象 如何在不更改 PHP 文件的情况下从 smarty 脚本访问 foo Thanks 如果你有一个名为 BASE 的常量变量 并且定义如下
  • PHP 与 MySQL 查询性能( if 、 函数 )

    我只看到这个artice http www onextrapixel com 2010 06 23 mysql has functions part 5 php vs mysql performance 我需要知道在这种情况下什么是最好的表
  • jQuery Mobile 表单验证

    我有一个移动网站 除了验证之外一切都工作正常 基本上我希望从用户那里获取值 然后在单独的页面 process php 上处理它们 但是 在这样做之前 我需要检查以确保字段已填充 我已经研究了几种方法来做到这一点 但似乎没有一种有效 我现在有
  • PHP HEREDoc (EOF) 语法在 Sublime Text 3 上突出显示与正斜杠的差异

    我不熟悉 Sublime Text 3 如何使用语法突出显示 例如 如果它纯粹依赖于主题 或者它内置于主题运行的标准中 但就我而言 使用 PHP 的 HERE 文档和转发存在一些语法突出显示差异斜线 一旦出现正斜杠 ST3 就会认为以下所有
  • Magento - 自定义支付模块

    这是一个非常普遍的问题 但这里是 我正在尝试在 Magento 中创建一个自定义支付模块 我创建了一个 常规 模块 可以连接到 Magento 事件 观察者模型 但是我如何告诉 Magento 将模块视为支付模块 以便它显示在管理后端和结账
  • 简单的 PHP 表单:电子邮件附件(代码 Golf)

    想象一下 一个用户想要在其网站上放置一个表单 该表单将允许网站访问者上传一个文件和一条简单的消息 该消息将立即通过电子邮件发送 即 该文件未存储在服务器上 或者如果该文件存储在服务器上 仅暂时 作为文件附件 并在邮件正文中添加注释 查看更多

随机推荐