YouTube API – OAuth and Upload Example

YouTube API - OAuth and Upload Example

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
download in package

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

<?php

// set error reporting level
if (version_compare(phpversion(), '5.3.0', '>=') == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
else
  error_reporting(E_ALL & ~E_NOTICE);

// http://code.google.com/apis/youtube/dashboard/gwt/index.html
$sDevKey = 'Your Youtube Developer Key';

$sWebPageUrl = 'http://www.script-tutorials.com/demos/283/index.php';
$sAuthUrl = urlencode($sWebPageUrl . '?action=auth');
$sOAuthUrl = "https://www.google.com/accounts/AuthSubRequest?next={$sAuthUrl}&scope=http%3A%2F%2Fgdata.youtube.com&session=0&secure=0";

// variables
$sToken = $sUploadUrl = $sUploadToken = $sNextUrl = $sVideoId = '';
$iUploadStatus = 0;

// actions
$sAction = $_REQUEST['action'];
switch ($sAction) {
    case 'auth': // step 1 - get access token and prepare form for sending to youtube with details of video
        $sToken = $_GET['token'];
        break;
    case 'prepare': // step 2 - send video details to youtube in order to obtain upload token and url

        // collect POSTed video details
        $sTitle = strip_tags($_POST['title']);
        $sDesc = strip_tags($_POST['description']);
        $sCategory = strip_tags($_POST['category']);
        $sKeywords = strip_tags($_POST['keywords']);
        $sToken = strip_tags($_POST['token']);

        // prepare data for youtube
        $sData = <<<EOF
<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom"
  xmlns:media="http://search.yahoo.com/mrss/"
  xmlns:yt="http://gdata.youtube.com/schemas/2007">
  <media:group>
    <media:title type="plain">{$sTitle}</media:title>
    <media:description type="plain">{$sDesc}</media:description>
    <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">{$sCategory}</media:category>
    <media:keywords>{$sKeywords}</media:keywords>
  </media:group>
</entry>
EOF;

        $sUplTokenUrl = "http://gdata.youtube.com/action/GetUploadToken";
        $aHeaders = array("POST /action/GetUploadToken HTTP/1.1",
            "Host: gdata.youtube.com",
            "Authorization: AuthSub token=" . $sToken,
            "X-GData-Key: key=" . $sDevKey,
            "Content-Length: " . strlen($sData),
            "Content-Type: application/atom+xml; charset=UTF-8"
        );
        $sUserAgent = $_SERVER['HTTP_USER_AGENT']; 

        // send request to youtube
        $oCurl = curl_init();
        curl_setopt($oCurl, CURLOPT_URL, $sUplTokenUrl);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $aHeaders);
        curl_setopt($oCurl, CURLOPT_HEADER, true);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 30);
        curl_setopt($oCurl, CURLOPT_USERAGENT, $sUserAgent);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $sData);
        curl_setopt($oCurl, CURLOPT_POST, true);
        $sXmlRes = curl_exec($oCurl);
        curl_close($oCurl);

        // lets find xml result and parse it in order to get upload url and token
        $sXmlSrc = substr($sXmlRes, strpos($sXmlRes, '<?xml'));
        if ($sXmlSrc != '') {
            $oXml = simplexml_load_string($sXmlSrc);
            $sUploadUrl = $oXml->url;
            $sUploadToken = $oXml->token;

            $sNextUrl = urlencode($sWebPageUrl . '?action=finish');
        }
        break;

    case 'finish': // step 3 - final. Our video has just posted to youtube, display results
        $iUploadStatus = (int)$_GET['status'];
        $sVideoId = $_GET['id'];
        break;
}

?>
<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>YouTube API - OAuth and Upload Example | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <header>
            <h2>YouTube API - OAuth and Upload Example</h2>
            <a href="http://www.script-tutorials.com/youtube-api-oauth-and-upload-example/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </header>
        <img src="ytb.png" class="ytb" alt="youtube" />

    <?php if (! $sToken && $sAction != 'finish'): ?>
        <center>
        <h1>Step 1. OAuth</h1>
        <h2>Please click <a href="<?= $sOAuthUrl ?>">this link</a> in order to authorize your account at youtube</h2>
        </center>
    <?php endif ?>

    <?php if ($sToken && !$sUploadToken): ?>
        <center>
        <h1>Step 2. Video info</h1>
        <h2>Now we should send video info to youtube in order to obtain proper upload token and url</h2>
        </center>
        <form method="post" action="index.php">
            <input type="hidden" name="token" value="<?php echo($sToken) ?>" />
            <input type="hidden" name="action" value="prepare" />
            <label for="title">Title:</label>
            <input type="text" name="title" value="Sample title of your video" />
            <label for="description">Description:</label>
            <input type="text" name="description" value="Sample description of your video" />
            <label for="category">Category:</label>
            <select name="category">
                <option value="Autos">Autos &amp; Vehicles</option>
                <option value="Comedy">Comedy</option>
                <option value="Education">Education</option>
                <option value="Entertainment">Entertainment</option>
                <option value="Film">Film &amp; Animation</option>
                <option value="Games">Gaming</option>
                <option value="Howto">Howto &amp; Style</option>
                <option value="Music">Music</option>
                <option value="News">News &amp; Politics</option>
                <option value="Nonprofit">Nonprofits &amp; Activism</option>
                <option value="People">People &amp; Blogs</option>
                <option value="Pets">Pets &amp; Animals</option>
                <option value="Tech">Science &amp; Technology</option>
                <option value="Sports">Sports</option>
                <option value="Travel">Travel &amp; Events</option>
            </select>
            <label for="keywords">Keywords:</label>
            <input type="text" name="keywords" value="Keywords" />
            <input type="submit" name="submit" value="Continue" />
        </form>
    <?php endif ?>

    <?php if ($sUploadUrl && $sUploadToken && $sNextUrl): ?>
        <center>
        <h1>Step 3. Upload file</h1>
        <h2>Now we should select video file and start upload</h2>
        </center>
        <form method="post" enctype="multipart/form-data" action="<?php echo $sUploadUrl . '?nexturl=' . $sNextUrl ?>">
            <input type="hidden" name="token" value="<?php echo($sUploadToken) ?>" />
            <label for="file">Select file to upload:</label>
            <input type="file" name="file" size="41" />
            <input type="submit" name="submit" value="Start upload" />
        </form>
    <?php endif ?>

    <?php if ($iUploadStatus == 200 && $sVideoId): ?>
        <center>
        <h1>Step 4. Final</h1>
        <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>
        </center>
    <?php elseif ($iUploadStatus): ?>
        <center>
        <h1>Step 4. Final</h1>
        <h2>Upload is failed. Error #<?php echo($iUploadStatus) ?></h2>
        </center>
    <?php endif ?>

    <?php if ($sToken || $sVideoId): ?>
        <br />
        <center><h2>(<a href="<?php echo $sWebPageUrl ?>">Click here to start over</a>)</h2></center>
    <?php endif ?>

</body>
</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

/* custom properties */
.ytb {
    display: block;
    margin: 40px auto;
}
form {
    background-color: #ddd;
    display: block;
    margin: 20px auto;
    padding: 15px;
    width: 400px;
}
label {
    display: block;
    margin-bottom: 5px;
}
input, select {
    border-style: groove;
    font-size: 16px;
    height: 25px;
    margin-bottom: 10px;
    width: 400px;

    /*css3 border radius*/
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;

    /* CSS3 Box sizing property */
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -o-box-sizing: border-box;
    box-sizing: border-box;
}

input[type=submit], input[type=file]{
    cursor: pointer;
    font-weight: bold;
    height: 35px;
    padding: 5px;
}

Live Demo
download in archive

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!

via Script Tutorials»Script Tutorials | Web Developer Tutorials | HTML5 and CSS3 Tutorials http://www.script-tutorials.com/youtube-api-oauth-and-upload-example/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s