YouTube API – OAuth and Upload Example

Today I would like to talk about video. Maybe you’ve got own video website, maybe you’re thinking about it, but anyway I think that our new information will be useful for you. As you know, video usually means that you need to have a lot of space at your hosting. And it is true in case if you store video files at your own server. But, in order to avoid all these difficulties (video storing and conversion), you can try to work with 3-rd party video hostings. As example youtube (or vimeo). In our new tutorial I will tell you how you can create youtube cross-uploader for your website.

In order to achieve our idea we will use
YouTube API v2.0 – Browser-based Uploading. In the beginning, we should prepare our own access token key. OAuth will help us with it. Then, we will display a form, where user can enters the video details (like title, category, description and keywords). When we have sent this information, Youtube will return us temporary upload token and url. Once we get it – we can start upload of selected video file.

Live Demo

[sociallocker]

download in package

[/sociallocker]


Now – download the source files and lets start coding !


Step 1. PHP

Now, please create empty index.php file and put next code:

index.php

001 <?php
002 // set error reporting level
003 if (version_compare(phpversion(), '5.3.0''>=') == 1)
004   error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
005 else
006   error_reporting(E_ALL & ~E_NOTICE);
008 $sDevKey 'Your Youtube Developer Key';
010 $sAuthUrl = urlencode($sWebPageUrl '?action=auth');
011 $sOAuthUrl "https://www.google.com/accounts/AuthSubRequest?next={$sAuthUrl}&scope=http%3A%2F%2Fgdata.youtube.com&session=0&secure=0";
012 // variables
013 $sToken $sUploadUrl $sUploadToken $sNextUrl $sVideoId '';
014 $iUploadStatus = 0;
015 // actions
016 $sAction $_REQUEST['action'];
017 switch ($sAction) {
018     case 'auth'// step 1 - get access token and prepare form for sending to youtube with details of video
019         $sToken $_GET['token'];
020         break;
021     case 'prepare'// step 2 - send video details to youtube in order to obtain upload token and url
022         // collect POSTed video details
023         $sTitle strip_tags($_POST['title']);
024         $sDesc strip_tags($_POST['description']);
025         $sCategory strip_tags($_POST['category']);
026         $sKeywords strip_tags($_POST['keywords']);
027         $sToken strip_tags($_POST['token']);
028         // prepare data for youtube
029         $sData = <<<EOF
030 <?xml version="1.0"?>
031 <entry xmlns="http://www.w3.org/2005/Atom"
032   xmlns:media="http://search.yahoo.com/mrss/"
034   <media:group>
035     <media:title type="plain">{$sTitle}</media:title>
036     <media:description type="plain">{$sDesc}</media:description>
037     <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">{$sCategory}</media:category>
038     <media:keywords>{$sKeywords}</media:keywords>
039   </media:group>
040 </entry>
041 EOF;
042         $sUplTokenUrl "http://gdata.youtube.com/action/GetUploadToken";
043         $aHeaders array("POST /action/GetUploadToken HTTP/1.1",
044             "Host: gdata.youtube.com",
045             "Authorization: AuthSub token=" $sToken,
046             "X-GData-Key: key=" $sDevKey,
047             "Content-Length: " strlen($sData),
048             "Content-Type: application/atom+xml; charset=UTF-8"
049         );
050         $sUserAgent $_SERVER['HTTP_USER_AGENT'];
051         // send request to youtube
052         $oCurl = curl_init();
053         curl_setopt($oCurl, CURLOPT_URL, $sUplTokenUrl);
054         curl_setopt($oCurl, CURLOPT_HTTPHEADER, $aHeaders);
055         curl_setopt($oCurl, CURLOPT_HEADER, true);
056         curl_setopt($oCurl, CURLOPT_TIMEOUT, 30);
057         curl_setopt($oCurl, CURLOPT_USERAGENT, $sUserAgent);
058         curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
059         curl_setopt($oCurl, CURLOPT_POSTFIELDS, $sData);
060         curl_setopt($oCurl, CURLOPT_POST, true);
061         $sXmlRes = curl_exec($oCurl);
062         curl_close($oCurl);
063         // lets find xml result and parse it in order to get upload url and token
064         $sXmlSrc substr($sXmlResstrpos($sXmlRes'<?xml'));
065         if ($sXmlSrc != '') {
066             $oXml = simplexml_load_string($sXmlSrc);
067             $sUploadUrl $oXml->url;
068             $sUploadToken $oXml->token;
069             $sNextUrl = urlencode($sWebPageUrl '?action=finish');
070         }
071         break;
072     case 'finish'// step 3 - final. Our video has just posted to youtube, display results
073         $iUploadStatus = (int)$_GET['status'];
074         $sVideoId $_GET['id'];
075         break;
076 }
077 ?>
078 <!DOCTYPE html>
079 <html lang="en" >
080     <head>
081         <meta charset="utf-8" />
082         <title>YouTube API - OAuth and Upload Example | Script Tutorials</title>
083         <link href="css/main.css" rel="stylesheet" type="text/css" />
084     </head>
085     <body>
086         <header>
087             <h2>YouTube API - OAuth and Upload Example</h2>
088             <a href="https://www.script-tutorials.com/youtube-api-oauth-and-upload-example/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
089         </header>
090         <img src="ytb.png" class="ytb" alt="youtube" />
091     <?php if (! $sToken && $sAction != 'finish'): ?>
092         <center>
093         <h1>Step 1. OAuth</h1>
094         <h2>Please click <a href="<?= $sOAuthUrl ?>">this link</a> in order to authorize your account at youtube</h2>
095         </center>
096     <?php endif ?>
097     <?php if ($sToken && !$sUploadToken): ?>
098         <center>
099         <h1>Step 2. Video info</h1>
100         <h2>Now we should send video info to youtube in order to obtain proper upload token and url</h2>
101         </center>
102         <form method="post" action="index.php">
103             <input type="hidden" name="token" value="<?php echo($sToken) ?>" />
104             <input type="hidden" name="action" value="prepare" />
105             <label for="title">Title:</label>
106             <input type="text" name="title" value="Sample title of your video" />
107             <label for="description">Description:</label>
108             <input type="text" name="description" value="Sample description of your video" />
109             <label for="category">Category:</label>
110             <select name="category">
111                 <option value="Autos">Autos &amp; Vehicles</option>
112                 <option value="Comedy">Comedy</option>
113                 <option value="Education">Education</option>
114                 <option value="Entertainment">Entertainment</option>
115                 <option value="Film">Film &amp; Animation</option>
116                 <option value="Games">Gaming</option>
117                 <option value="Howto">Howto &amp; Style</option>
118                 <option value="Music">Music</option>
119                 <option value="News">News &amp; Politics</option>
120                 <option value="Nonprofit">Nonprofits &amp; Activism</option>
121                 <option value="People">People &amp; Blogs</option>
122                 <option value="Pets">Pets &amp; Animals</option>
123                 <option value="Tech">Science &amp; Technology</option>
124                 <option value="Sports">Sports</option>
125                 <option value="Travel">Travel &amp; Events</option>
126             </select>
127             <label for="keywords">Keywords:</label>
128             <input type="text" name="keywords" value="Keywords" />
129             <input type="submit" name="submit" value="Continue" />
130         </form>
131     <?php endif ?>
132     <?php if ($sUploadUrl && $sUploadToken && $sNextUrl): ?>
133         <center>
134         <h1>Step 3. Upload file</h1>
135         <h2>Now we should select video file and start upload</h2>
136         </center>
137         <form method="post" enctype="multipart/form-data" action="<?php echo $sUploadUrl . '?nexturl=' . $sNextUrl ?>">
138             <input type="hidden" name="token" value="<?php echo($sUploadToken) ?>" />
139             <label for="file">Select file to upload:</label>
140             <input type="file" name="file" size="41" />
141             <input type="submit" name="submit" value="Start upload" />
142         </form>
143     <?php endif ?>
144     <?php if ($iUploadStatus == 200 && $sVideoId): ?>
145         <center>
146         <h1>Step 4. Final</h1>
147         <h2>Your video has just uploaded to youtube and available <a href="http://www.youtube.com/watch?v=<?php echo($sVideoId) ?>" target="_blank">here</a></h2>
148         </center>
149     <?php elseif ($iUploadStatus): ?>
150         <center>
151         <h1>Step 4. Final</h1>
152         <h2>Upload is failed. Error #<?php echo($iUploadStatus) ?></h2>
153         </center>
154     <?php endif ?>
155     <?php if ($sToken || $sVideoId): ?>
156         <br />
157         <center><h2>(<a href="<?php echo $sWebPageUrl ?>">Click here to start over</a>)</h2></center>
158     <?php endif ?>
159 </body>
160 </html>

Please pay attention, in the most beginning, you should create your own product in order to create your youtube developer key. So, please go to this page and make your own key, and after – put your key here: $sDevKey = ‘Your Youtube Developer Key’;

I hope that my code is easy enough. All the process is separated into three logical steps: get access token, send video info and receive upload token, and upload video file. That’s all.

Step 2. CSS

Now we need to stylize our page elements:

css/main.css

01 /* custom properties */
02 .ytb {
03     displayblock;
04     margin40px auto;
05 }
06 form {
07     background-color#ddd;
08     displayblock;
09     margin20px auto;
10     padding15px;
11     width400px;
12 }
13 label {
14     displayblock;
15     margin-bottom5px;
16 }
17 input, select {
18     border-stylegroove;
19     font-size16px;
20     height25px;
21     margin-bottom10px;
22     width400px;
23     /*css3 border radius*/
24     -moz-border-radius: 5px;
25     -ms-border-radius: 5px;
26     -o-border-radius: 5px;
27     -webkit-border-radius: 5px;
28     border-radius: 5px;
29     /* CSS3 Box sizing property */
30     -moz-box-sizing: border-box;
31     -webkit-box-sizing: border-box;
32     -o-box-sizing: border-box;
33     box-sizing: border-box;
34 }
35 input[type=submit], input[type=file]{
36     cursorpointer;
37     font-weightbold;
38     height35px;
39     padding5px;
40 }

Live Demo

Conclusion

And again, we have made our next really useful tutorial. Sure that this information will be useful for your own projects. Good luck in your work!