session - PHP Youtube API upload video code sample uploads twice -


i using php code sample uploading video provided youtube, can found here: https://developers.google.com/youtube/v3/code_samples/php#upload_a_video

however, when session starts, requires user authorise it, takes authorise page, redirects back. on doing this, uploads twice, assume trying upload video not when not authorised. double uploads when authorising, , not when page reloaded , session still valid.

how stop initial duplicate upload?

you can use following code upload file after user has signin when user click submit button path defined in text input :

<?php /**  * library requirements  *  * 1. install composer (https://getcomposer.org)  * 2. on command line, change directory (api-samples/php)  * 3. require 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 = "";  /*  * can acquire oauth 2.0 client id , client secret  * {{ google cloud console }} <{{ https://cloud.google.com/console }}>  * more information using oauth 2.0 access google apis, please see:  * <https://developers.google.com/youtube/v3/guides/authentication>  * please ensure have enabled youtube data api 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 object used make api requests. $youtube = new google_service_youtube($client); // check if auth token exists 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 ensure access token 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 snippet title, description, tags , category id       // create asset resource , set snippet metadata , type.       // example sets video's title, description, keyword tags, ,       // 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 video's status "public". valid statuses "public",       // "private" , "unlisted".       $status = new google_service_youtube_videostatus();       $status->privacystatus = "private";        // associate snippet , status objects new video resource.       $video = new google_service_youtube_video();       $video->setsnippet($snippet);       $video->setstatus($status);        // specify size of each chunk of data, in bytes. set higher value       // reliable connection fewer chunks lead faster uploads. set lower       // value better recovery on less reliable connections.       $chunksizebytes = 1 * 1024 * 1024;        // setting defer flag true tells client return request can called       // ->execute(); instead of making api call immediately.       $client->setdefer(true);        // create request api's videos.insert method create , upload video.       $insertrequest = $youtube->videos->insert("status,snippet", $video);        // create mediafileupload object resumable uploads.       $media = new google_http_mediafileupload(           $client,           $insertrequest,           'video/*',           null,           true,           $chunksizebytes       );       $media->setfilesize(filesize($videopath));        // read media file , upload chunk chunk.       $status = false;       $handle = fopen($videopath, "rb");       while (!$status && !feof($handle)) {         $chunk = fread($handle, $chunksizebytes);         $status = $media->nextchunk($chunk);       }        fclose($handle);        // if want make other calls after file upload, set setdefer 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 specified or file doesn't exist";     file_put_contents('php://stderr', print_r("no path 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 user hasn't authorized app, initiate 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 path video 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 page gets refresh or if user clicks button mistake 1 more time, re-upload video. check this post deal duplicated video issue


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -