YouTube API – OAuth and Upload Example

YouTube API – OAuth and Upload Example

5 60315
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:


// set error reporting level
if (version_compare(phpversion(), '5.3.0', '>=') == 1)
  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
  error_reporting(E_ALL & ~E_NOTICE);
$sDevKey = 'Your Youtube Developer Key';
$sWebPageUrl = '';
$sAuthUrl = urlencode($sWebPageUrl . '?action=auth');
$sOAuthUrl = "{$sAuthUrl}&";
// 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'];
    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=""
    <media:title type="plain">{$sTitle}</media:title>
    <media:description type="plain">{$sDesc}</media:description>
    <media:category scheme="">{$sCategory}</media:category>
        $sUplTokenUrl = "";
        $aHeaders = array("POST /action/GetUploadToken HTTP/1.1",
            "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);
        // 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');
    case 'finish': // step 3 - final. Our video has just posted to youtube, display results
        $iUploadStatus = (int)$_GET['status'];
        $sVideoId = $_GET['id'];
<!DOCTYPE html>
<html lang="en" >
        <meta charset="utf-8" />
        <title>YouTube API - OAuth and Upload Example | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />
            <h2>YouTube API - OAuth and Upload Example</h2>
            <a href="" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        <img src="ytb.png" class="ytb" alt="youtube" />
    <?php if (! $sToken && $sAction != 'finish'): ?>
        <h1>Step 1. OAuth</h1>
        <h2>Please click <a href="<?= $sOAuthUrl ?>">this link</a> in order to authorize your account at youtube</h2>
    <?php endif ?>
    <?php if ($sToken && !$sUploadToken): ?>
        <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>
        <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>
            <label for="keywords">Keywords:</label>
            <input type="text" name="keywords" value="Keywords" />
            <input type="submit" name="submit" value="Continue" />
    <?php endif ?>
    <?php if ($sUploadUrl && $sUploadToken && $sNextUrl): ?>
        <h1>Step 3. Upload file</h1>
        <h2>Now we should select video file and start upload</h2>
        <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" />
    <?php endif ?>
    <?php if ($iUploadStatus == 200 && $sVideoId): ?>
        <h1>Step 4. Final</h1>
        <h2>Your video has just uploaded to youtube and available <a href="<?php echo($sVideoId) ?>" target="_blank">here</a></h2>
    <?php elseif ($iUploadStatus): ?>
        <h1>Step 4. Final</h1>
        <h2>Upload is failed. Error #<?php echo($iUploadStatus) ?></h2>
    <?php endif ?>
    <?php if ($sToken || $sVideoId): ?>
        <br />
        <center><h2>(<a href="<?php echo $sWebPageUrl ?>">Click here to start over</a>)</h2></center>
    <?php endif ?>

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:


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


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!



  1. Hello, first of all congratulations for the great example, but I have a doubt and would like to be able to count on your help! I am developing a website where I’d like users efetuassem upload your videos directly to my youtube channel that they had no need to authenticate yourself, could you tell me which method for using and enjoying not having the need to present the screen user authentication? I thank you!

    • Hello Cristiano,
      I’m not sure that this is possible, because, authentication usually mean that you should login to 3rd party service (youtube) in order to upload something. How can you login without knowing your credentials?

  2. Is it just me or is this link broken:

Leave a Reply