Premature end of file, direct upload youtube - php

I am trying to upload a video to youtube, using the direct upload method as explained here, at documentation.
I have included my developer key correctly, and am getting the session token too without any problem. The problem appears when it directs me to the upload page with the token. Instead of uploading and returning with the video id, it shows me a single line,
Premature end of file.
I am new to zend as well as using youtube api's for the first time, I managed to work out authentication and few errors, that were shown but I have no idea, why or where is this problem.
Here is my php file,
<?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');
Zend_Loader::loadClass('Zend_Uri_Http');
function getAuthSubRequestUrl()
{
$next = 'http://localhost/trial/trial.php';
$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 'Login to YouTube API!';
//if token has been requested but not saved to a session then save the new token to a session
} else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
$_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
}
if(isset($_SESSION['sessionToken'])) {
$clientLibraryPath = '/library';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $clientLibraryPath);
$sessionToken = $_SESSION['sessionToken'];
$developerKey = 'my-key-here'; //I have inserted the key correctly.
$httpClient = new Zend_Gdata_HttpClient();
$httpClient->setAuthSubToken($sessionToken);
$yt = new Zend_Gdata_YouTube($httpClient, '23', '234', $developerKey);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$file= '../path_to_file/filename.mp4';
$file = realpath($file);
$filesource = $yt->newMediaFileSource($file);
// create a new Zend_Gdata_App_MediaFileSource object
$filesource = $yt->newMediaFileSource('file.mov');
$filesource->setContentType('video/quicktime');
// set slug header
$filesource->setSlug('file.mov');
$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie');
$myVideoEntry->setVideoCategory('Entertainment');
$myVideoEntry->SetVideoTags('testme');
$myVideoEntry->setVideoDeveloperTags(array('tester', 'test'));
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
try {
$newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
}
?>
Thanks. Please ask for further explanations or information regarding the problem or code if required.

I suggest to use the Data API instead and utilize the resumable upload. Here's a PHP upload example.

Related

php server google drive download file in background

I need form PHP level, in background without user interaction login on google drive and get files list. I found similar topic and code for question working, but is required handly login, where I need login from php in background.
In second post with code for possibly login witout user interaction, but I don't know where is bug.
My code PHP:
<?php
require_once 'vendor/autoload.php';
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_DriveService.php';
require_once 'src/auth/Google_AssertionCredentials.php';
$client_email = 'xxxxxx#xxxxxxxxxxxxx.xxx.gserviceaccount.com';
$private_key = file_get_contents('key.p12');
$user_to_impersonate = 'xxxxxxxxxxxxxxx#gmail.com';
$scopes = array('https://www.googleapis.com/auth/drive');
$credentials = new Google_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Drive($client);
$files = $service->files->listFiles();
echo "count files=".count($files)."<br>";
foreach( $files as $item ) {
echo "title=".$item['title']."<br>";
}
?>
Vendor directory I get from this instruction, and other files I get from this GitHub
I had problem with function Google_Auth_AssertionCredentials, PHP hasn't file with this function. I found that file src/auth/Google_AssertionCredentials.php has similar function Google_AssertionCredentials. I included Google_AssertionCredentials.php file and changed function name.
In finally I have new error:
PHP Fatal error: Cannot call constructor in
\google_drive\vendor\google\apiclient-services\src\Google\Service\Drive.php
on line 75
I don't know what doing again. I tried many other metod for login on google drive, eg. load file list GET method with API_KEY, or via json file.
As result I want get file list, download them. edit and upload.
Any sugestions?
EDIT:
I have part sucess. I found liblary this, and them work with this code:
<?php
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
session_start();
require_once '/google-api-php-client/autoload.php';
$client_email = 'xxxx#xxxxx.iam.gserviceaccount.com';
$user_to_impersonate = 'xxxxxx#gmail.com';
$private_key = file_get_contents('key.p12');
$scopes = array('https://www.googleapis.com/auth/drive');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer',
$user_to_impersonate
);
$client = new Google_Client();
if(isset($_SESSION['service_token'])==false && $_SESSION['service_token']=='') {
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
$_SESSION['service_token'] = $client->getAccessToken();
}
if(isset($_SESSION['service_token']) && $_SESSION['service_token']) {
$client->setAccessToken($_SESSION['service_token']);
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
$_SESSION['service_token'] = $client->getAccessToken();
}
$service = new Google_Service_Drive($client);
print_r(retrieveAllFiles($service));
}
?>
And in result I have only one file [originalFilename] => Getting started, this is PDF, but I don't see this file on Gogle dirve. On google drive I uploaded file: README.md.
I'm not sure, but maybe this file is on ` 'xxxx#xxxxx.iam.gserviceaccount.com' and script not logged to 'xxxxxx#gmail.com'?

Twitter API in PHP using codebird

I need to incorporate twitter feature in a project of mine. Among all the libraries and wrappers, codebird seemed convenient. I tried to do the basic authentication using codes from their example, but upon uploading the files on the server, i cant get to access them at all. It shows error 500 in server and i cant test them on localhost.
the index.php file
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
the callback.php
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
if(isset($_SESSION['oauth_token'] && isset($_SESSION['oauth_token_secret']))){
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); // see above
$reply = (array) $cb->statuses_homeTimeline();
print_r($reply);
}
else {
echo 'necessary session variables couldnt be found!';
}
?>
This might be a really noob question as i have only basic knowledge in PHP, but any help would be much appriciated, please.

How to set advanced settings while uploading videos to Youtube using google-youtube api php

I have created the php script below that uploads videos to youtube and it uploads fine.
I would like to be able to set advanced settings to the uploaded video as follows:
Allow comments should be "approved" not "All"
I also need to be able to set the video location(this would come from
the database from my site)
I should also need to be able to set the recording date(to the date
of the upload)
I also don't want the video statistics to be publicly visible
I have looked around, but i cannot find any documentation on this from google, and i think google have not provided complete documentation for the API.
Any links will also do. Thanks
require_once '../google_api/Google_Client.php';
require_once '../google_api/contrib/Google_YouTubeService.php';
$OAUTH2_CLIENT_ID = '514750847005.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = '9mvQL0NPv1zEOty0tZw71O4t';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri("{$redirect}");
$youtube = new Google_YoutubeService($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
try {
$snippet = new Google_VideoSnippet();
$snippet->setTitle($title);
$snippet->setDescription($desc);
$snippet->setTags($tags);
$snippet->setCategoryId(22);
$status = new Google_VideoStatus();
$status->privacyStatus = "public";
$today = date("Y-m-d\TH:i:s");
$recordingDetails = new Google_VideoRecordingDetails();
$recordingDetails->setRecordingDate($today);
$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$video->setRecordingDetails($recordingDetails);
// Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
// for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
$chunkSizeBytes = 1 * 1024 * 1024;
// Create a MediaFileUpload with resumable uploads
$media = new Google_MediaFileUpload('video/*', null, true, $chunkSizeBytes);
$media->setFileSize(filesize($vd_file));
// Create a video insert request
$insertResponse = $youtube->videos->insert("status,snippet", $video, array('mediaUpload' => $media));
$uploadStatus = false;
// Read file and upload chunk by chunk
$handle = fopen($vd_file, "rb");
while (!$uploadStatus && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$uploadStatus = $media->nextChunk($insertResponse, $chunk);
}
fclose($handle);
msg_add('suces', 'message', 'Youtube video upload was successful');
} catch (Google_ServiceException $e) {
$message = sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
msg_add('err', 'message', $message);
} catch (Google_Exception $e) {
$message = sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
msg_add('err', 'message', $message);
}
What you are doing is simply a video->insert call. You are editing snippet, status and recordingDetails. You can do more by adding the other fields to the VIDEOS resource.
Fill in any field of the VIDEOS resource before inserting, that should do.
I ran across a similar situation where I was trying to set the location on insert but it was not working. I got my code to correctly set location by including "recordingDetails" in the part parameter which is a comma separated list (docs). I am using C#, so for me it looks like this:
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status,recordingDetails", fileStream, "video/*");
From your sample it looks like in php this would be
$insertResponse = $youtube->videos->insert("status,snippet,recordingDetails", $video, array('mediaUpload' => $media));
Allow comments should be "approved" not "All"
It seems that's a youtube bug:
https://code.google.com/p/gdata-issues/issues/detail?id=7664

Youtube API 401 Error

I'm using the Youtube API to try some things out and I can't get to do anything without getting the error. Expected response code is 200, got 401: User authentication required.
I have authenticated my Youtube channel though
session_start();
$clientLibraryPath = 'Youtube/library';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $clientLibraryPath);
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
function getAuthSubRequestUrl()
{
$next = 'LINK';
$scope = 'http://gdata.youtube.com';
$secure = false;
$session = true;
return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
}
function getAuthSubHttpClient()
{
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
echo 'Login!';
return;
} else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
$_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
}
$httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
return $httpClient;
}
getAuthSubHttpClient();
$cID = "Client ID";
$aID = "App ID";
$dK = "DEV KEY"; // Hidden
$yt = new Zend_Gdata_YouTube($httpClient, $aID, $cID, $dK);
Anyone know what I'm doing wrong here to login into my account?
Make sure you have your code hosted in the exact same URL as you set in the Google Code Console
If your javascript origins is set to http://example.com, make sure your code isn't being hosted at http://example.com/something or http://something.example.com! This seemed to work for me :)

Get the Video URL after uploading a video to Youtube using Data API - php

I'm trying to upload a video to YouTube using the PHP Data API
$yt = new Zend_Gdata_YouTube($httpClient);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource('mytestmovie.mov');
$filesource->setContentType('video/quicktime');
$filesource->setSlug('mytestmovie.mov');
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle('My Test Movie');
$myVideoEntry->setVideoDescription('My Test Movie');
// Note that category must be a valid YouTube category !
$myVideoEntry->setVideoCategory('Comedy');
// Set keywords, note that this must be a comma separated string
// and that each keyword cannot contain whitespace
$myVideoEntry->SetVideoTags('cars, funny');
// Optionally set some developer tags
$myVideoEntry->setVideoDeveloperTags(array('mydevelopertag',
'anotherdevelopertag'));
// Optionally set the video's location
$yt->registerPackage('Zend_Gdata_Geo');
$yt->registerPackage('Zend_Gdata_Geo_Extension');
$where = $yt->newGeoRssWhere();
$position = $yt->newGmlPos('37.0 -122.0');
$where->point = $yt->newGmlPoint($position);
$myVideoEntry->setWhere($where);
// Upload URI for the currently authenticated user
$uploadUrl =
'http://uploads.gdata.youtube.com/feeds/users/default/uploads';
// Try to upload the video, catching a Zend_Gdata_App_HttpException
// if availableor just a regular Zend_Gdata_App_Exception
try {
$newEntry = $yt->insertEntry($myVideoEntry,
$uploadUrl,
'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
Does anyone know how to get the URL of the uploaded video from the $newEntry object.
Any help will be appreciated :)
Try this:
try {
$newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl,
'Zend_Gdata_YouTube_VideoEntry');
$id = $newEntry->getVideoId(); // YOUR ANSWER IS HERE :)
echo $id;
}

Categories