提示登录后如何将 $_POST 数据传递到 youtube 上传脚本

Posted

技术标签:

【中文标题】提示登录后如何将 $_POST 数据传递到 youtube 上传脚本【英文标题】:How to pass $_POST data to youtube upload script AFTER being prompted to sign in 【发布时间】:2019-03-14 09:27:51 【问题描述】:

我的 wordpress 页面上有一个脚本,可让用户在我的网站上创建视频帖子,然后将视频上传到他们的 youtube。

用户单击我网站上的一个按钮,该按钮将表单数据从隐藏的输入字段发送到运行 youtube 上传 api 脚本的新窗口,如果用户未登录,它会要求他们这样做。

我遇到的问题是,当用户必须登录并被重定向回页面时,帖子值会丢失并导致我的上传脚本失败,因为它们应该定义视频路径。

我尝试了多种不同的方法来尝试传递变量,但是似乎没有任何效果,登录后数据永远不会传递到页面。

如果已经登录,它总是有效的。单击按钮时,变量会被传递。

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


$dirpath = $_SERVER["DOCUMENT_ROOT"] ."/wp-content/uploads/".$authorID."/".$vidID;

// Set session variables
$_SESSION["favcolor"] = $_POST['vid_id'];

file_put_contents($dirpath."/videoTitle.txt", $videoTitle);
file_put_contents($dirpath."/authorID.txt", $authorID);
file_put_contents($dirpath."/vidID.txt", $vidID);
file_put_contents($dirpath."/dir.txt", $dirpath);

$vID = file_get_contents($dirpath.'/vidID.txt');
$auID = file_get_contents($dirpath.'/authorID.txt');

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) 
  $htmlBody = '';
  $htmlBody2 = '';
  try

    // REPLACE this value with the path to the file you are uploading.
    $videoPath = $_SERVER["DOCUMENT_ROOT"] ."/wp-content/uploads/".$auID."/". $vID."/output-".$vID.".mp4";

上面显示了我正在尝试的尝试,以便我可以定义 videoPath。我在尝试修改之前的原始脚本--

<?php
//require_once $_SERVER['DOCUMENT_ROOT'] . '/gap/google-api-php-client/vendor/autoload.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';

set_include_path($_SERVER['DOCUMENT_ROOT'] . '/gap/google-api-php-client/');
require_once 'src/Google/Client.php';
require_once 'src/Google/Service/YouTube.php';

session_start();

$application_name = 'XXXX'; 
$OAUTH2_CLIENT_ID = 'XXXX';
$OAUTH2_CLIENT_SECRET = 'XXXX';

$videoTitle = $_POST['titlez'];
$authorID = $_POST['a_id'];
$vidID = $_POST['vid_id'];

$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('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
    FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setAccessType("offline");
$client->setApprovalPrompt("force");

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


get_header();
global $current_user, $imic_options; // Use global
get_currentuserinfo(); // Make sure global is set, if not set it.

if ((user_can($current_user, "administrator"))||(user_can($current_user, "edit_others_posts")) ):


// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) 
  $htmlBody = '';
  try
    // REPLACE this value with the path to the file you are uploading.
    $videoPath = $_SERVER["DOCUMENT_ROOT"] ."/uploads/".$authorID."/".$vidID."/output-".$vidID.".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</li>',
        $status['snippet']['title']);
    $htmlBody .= sprintf('<li><a href="https://www.youtube.com/watch?v=%s" target="_blank">Video Link</a></li>',
        $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[$tokenSessionKey] = $client->getAccessToken();
 elseif ($OAUTH2_CLIENT_ID == '(I never changed this)REPLACE_ME') 
  $htmlBody = <<<END
  <h3>Client Credentials Required</h3>
  <p>
    You need to set <code>\$OAUTH2_CLIENT_ID</code> and
    <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
  <p>
END;
 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;

?>

<div id="ytu-container">
<?=$htmlBody?>
</div>

<?php
else: echo imic_unidentified_agent();
endif;
get_footer();
?>

那么如何在登录后将变量传递给页面。

【问题讨论】:

【参考方案1】:

您可以使用 sessionStorage 或 localStorage 保存变量并在用户被重定向回页面时检索它们。

【讨论】:

【参考方案2】:

我想通了,用 sessionStorage 解决了这个问题。我第一次尝试它时它不起作用的原因是因为我的代码在脚本中的位置。通过移动 $_session 代码,我可以设置它。

我将它从脚本顶部移到脚本中的以下位置 -

// 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
$_SESSION["video"] = $_POST['vid_id'];
$_SESSION["author"] = $_POST['a_id'];
$_SESSION["title"] = $_POST['ytu_title'];    
$vidID = $_SESSION["video"];

  $authUrl = $client->createAuthUrl();

  $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;

在 youtube 脚本中寻找这个 -

// 如果用户没有授权应用,则启动 OAuth 流程

这是脚本的一部分,如果尚未登录,则提示用户登录。所以这是他们看到的第一页,因此请确保在此处设置变量。

然后我就可以在脚本的其他部分使用变量了 -

$videoPath = $_SERVER["DOCUMENT_ROOT"] ."/wp-content/uploads/" . $_SESSION["author"] . "/" . $_SESSION["video"] . "/output-" . $_SESSION["video"] . ".mp4";

$snippet->setTitle($_SESSION["title"]);

【讨论】:

以上是关于提示登录后如何将 $_POST 数据传递到 youtube 上传脚本的主要内容,如果未能解决你的问题,请参考以下文章

使用 Azure AD 在两者之间登录时,如何将查询字符串参数或 POST 数据传递到重定向站点?

如何在php网页中通过一个表单让使用者输入数据提交后把输入的数据传递到mysql数据库中?

如何在 jmeter 中发送 $_POST 数据?

在简单的 $var 中传递 $_POST var 后测试 is_int 不起作用

关于PHP中POST传递参数问题

login_01