Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass $_POST data to youtube upload script AFTER being prompted to sign in

I have a script on my wordpress page that lets users create video posts on my site and then upload the video to their youtube.

The user clicks on a button on my site which sends form data from hidden input fields to a new window running the youtube upload api script, and if the user is not logged in it asks them to do so.

The issue Im having though is that when a user has to log in and is redirected back to the page, the post values are lost and are causing my upload script to fail since they are suppose to define the video path.

I've tried multiple attempts of different ways to try and get the variables passed, however nothing seems to work, the data never passes to the page after login.

If already logged in though, it always works. when clicking the button the variables get passed.

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

The above shows the attempts I am trying so that I can define the videoPath. My original script before trying to modify --

<?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();
?>

So how can I pass the variables to the page AFTER logging in.

like image 588
730wavy Avatar asked Oct 09 '18 14:10

730wavy


People also ask

How can I upload my video in resume?

If you had to quit your upload for any reason, you have up to 24 hours to continue uploading where you left off. Return to youtube.com/upload and select the same file from your computer to continue.


1 Answers

you can use sessionStorage or localStorage to save the variables and retrieve them when the user is redirected back to the page.

like image 83
CecilMerrell aka bringrainfire Avatar answered Oct 01 '22 02:10

CecilMerrell aka bringrainfire