giovedì 14 luglio 2011

PHP class to manage Youtube contents

A few days ago I played with youtube API for a web application, but the official documentation seems not to be ready to use:
so I decided to release my PHP class, maybe can be useful!

First of all you need:
- an youtube account
- a web server with Zend GData PHP library
- a google development key
- the php file with my class

This is a simple code both for direct upload or a browser upload:

//YouTube data, remember that developerKey is public 
$developerKey = 'your key';
$authenticationURL = '';
$uploadURL = '';
$Username = 'youtube_account';
$Password = 'youtube password'; 
$YoutubeSource = 'YourApplicationName';
$applicationId = 'AppID:AppID';

$ytvideo = new YouTube_API($developerKey, $authenticationURL, $applicationId);
ytvideo->connect($Username, $Password, $YoutubeSource);

$title = 'Write here title';
$description = 'Write here description';
$category = 'Write here a valid YouTube category(see youtbe class for details)';
$tags = 'Write here a comma-separated string';

Now you can upload a video from your own web server to that of youtube server:
$result = $ytvideo->DirectUpload($miofile,  $applicationId, $title, $description, $category, $tags);
echo "VideoID: ".$ytvideo->newEntry->getVideoId();

Or you can upload a video from user's web browser to the server of youtube directly:
$nextUrl = 'http://your_site/upload_status.php';
$tokenArray = $ytvideo->BrowserUpload($miofile, $title, $description, $category, $tags, false, "");
$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];

$form = '<div id="uploada"><form onSubmit="javascript:return checkForm();" style="position:relative; top:12px; left:35px;" action="'. $postUrl .'?nexturl='. $nextUrl .
'" method="post" enctype="multipart/form-data" name="form_upload" id="form_upload">'. 
'<input name="file" type="file" id="video_uploaded" name="video_uploaded"/>'. 
'<input name="token" type="hidden" value="'. $tokenValue .'"/>'.
'<input value="Upload Video" type="submit" />'. 
echo $form;
when the download is finished, youtube redirects the user's browser to : http://your_site/upload_status.php
so here you can check the operation status:

if (isset($_GET['status']))

if ($ystatus==200)
echo "Upload succefull, id video is:".$id_video;
echo "Upload error";

The php class is very simple and still incomplete. You can change the visibility of a video (public or private), the video description or delete it permanently as well, ex:
$ytvideo = new YouTube_API($developerKey, $authenticationURL, $uploadURL);

$ytvideo->connect($Username, $Password, $YoutubeSource);

good luck! :-)