Uploading videos to YouTube from your website in PHP

Today, I’m going to talk about uploading videos to YouTube in PHP from your website. First, you’ll need a YouTube account and a developer key. To get your developer key, visit http://code.google.com/apis/youtube/dashboard/

Let’s begin with the codes

First, we would need our YouTube account and your developer key,

$youtube_email = "youtube-email"; // Change this to your youtube sign in email.
$youtube_password = "your-youtube-password"; // Change this to your youtube sign in password.
    // Developer key: Get your key here: http://code.google.com/apis/youtube/dashboard/.
$key = "your-dev-key";

Next we need to setup CURL to access YouTube servers and login.

    $source = 'Akpos Jokes'; // A short string that identifies your application for logging purposes.
    $postdata = "Email=".$youtube_email."&Passwd=".$youtube_password."&service=youtube&source=" . $source;
    $curl = curl_init( "https://www.google.com/youtube/accounts/ClientLogin" );
    curl_setopt( $curl, CURLOPT_HEADER, "Content-Type:application/x-www-form-urlencoded" );
    curl_setopt( $curl, CURLOPT_POST, 1 );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, $postdata );
    curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 1 );
    $response = curl_exec( $curl );
    curl_close( $curl );

Below is the code that enables us to get our Access Token and username from YouTube.

list( $auth, $youtubeuser ) = explode( "\n", $response );
list( $authlabel, $authvalue ) = array_map( "trim", explode( "=", $auth ) );
list( $youtubeuserlabel, $youtubeuservalue ) = array_map( "trim", explode( "=", $youtubeuser ) );

Once we are authenticated and have gotten our Token we need to begin uploading the videos. Here is the Schema:

<?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">Bad Wedding Toast</media:title>
    <media:description type="plain">
      I gave a bad toast at my friend's wedding.
    </media:description>
    <media:category
      scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People
    </media:category>
    <media:keywords>toast, wedding</media:keywords>
  </media:group>
</entry>

Now, to push this in PHP we do this:

$youtube_video_title = $video_title; // This is the uploading video title.
    $youtube_video_description = $video_description; // This is the uploading video description.   
    $youtube_video_keywords = "jokes ".$video_keywords; // This is the uploading video keywords.
    $youtube_video_category = "Comedy"; // This is the uploading video category. There are only certain categories that are accepted. See below 
    
    $data = '<?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">' . stripslashes( $youtube_video_title ) . '</media:title>
                    <media:description type="plain">' . stripslashes( $youtube_video_description ) . '</media:description>
                    <media:category
                      scheme="http://gdata.youtube.com/schemas/2007/categories.cat">'.$youtube_video_category.'</media:category>
                    <media:keywords>'.$youtube_video_keywords.'</media:keywords>
                  </media:group>
                </entry>';

    $headers = array( "Authorization: GoogleLogin auth=".$authvalue,
                 "GData-Version: 2",
                 "X-GData-Key: key=".$key,
                 "Content-length: ".strlen( $data ),
                 "Content-Type: application/atom+xml; charset=UTF-8" );

$curl = curl_init( "http://gdata.youtube.com/action/GetUploadToken");
curl_setopt( $curl, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"] );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_TIMEOUT, 10 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $curl, CURLOPT_POST, 1 );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $data );
curl_setopt( $curl, CURLOPT_REFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt( $curl, CURLOPT_HEADER, 0 );

$response = simplexml_load_string( curl_exec( $curl ) );
curl_close( $curl );

Once we get the response after setting our Category, Video Title, Description and keywords, we get a token that allows up to upload the video file to YouTube’s servers.

The $response variable receives the response from YouTube and we can then access all the information we need to upload the video e.g $response->token is our token $response->url is the url where we upload the video file to.

Here are the acceptable categories for a video on YouTube:

        Film
        Autos
        Music
        Animals
        Sports
        Travel
        Shortmov
        Games
        Videblog
        People
        Comedy
        Entertainment
        News
        Howto
        Education
        Tech
        Nonprofit
        Movies
        Movies_anime_action
        Movies_action_adventure
        Movies_classics
        Movies_comedy
        Movies_documentary
        Moves_drama
        Movies_family
        Movies_foreign
        Movies_horror
        Movies_sci_fi_fantasy
        Movies_thriller
        Movies_shorts
        Shows
        Trailers

The uploading process

The response we get from this allows us to get the url to upload the video to. Now to upload the video, we need a form and the YouTube url where our video will be uploaded to.

Here is our upload form.

<body>
        
        <?php        
        //If the 1st step form has been submited, run the token script.
        if( isset( $_POST['video_title'] ) && isset( $_POST['video_description'] ) ) {
            $video_title = stripslashes( $_POST['video_title'] );
            $video_description = stripslashes( $_POST['video_description'] );
      $video_keywords = stripslashes( $_POST['video_keywords'] );
            include_once( 'get_youtube_token.php' ); //this gets our $response above
        }
        
        // Specifies the url that youtube will return to. The data it returns are as get variables         
        $nexturl = "http://your-url/";
        // These are the get variables youtube returns once the video has been uploaded.
        $unique_id = $_GET['id'];
        $status = $_GET['status'];
        ?>
        
        <!-- Step 1 of the youtube upload process -->
        <?php if( empty( $_POST['video_title'] ) && $unique_id == "" ) : ?>                    
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">                
                <label for="video_title">Video Title</label>
                <input type="text" name="video_title" maxlength="100" />
                <label for="video_description">Video Description</label>
                <textarea id="video-description" maxlength="2000" name="video_description"></textarea>
         <label for="video_title">Video Keywords(e.g jokes, funny, etc)</label>
                <input type="text" name="video_keywords" maxlength="20"/>
                <input type="submit" value="Step 2" />
            </form> <!-- /form -->

        <!-- Step 2 -->           
        <?php elseif( $response->token != '' ) : ?>                        
            <h4>Title:</h4>
            <p><?php echo $video_title; ?></p>
            <h4>Description:</h4>
            <p><?php echo $video_description; ?></p>
       <h4>Keywords:</h4>
            <p><?php echo $video_keywords; ?></p>
            <form action="<?php echo( $response->url ); ?>?nexturl=<?php echo( urlencode( $nexturl ) ); ?>" method="post" enctype="multipart/form-data">
                <p class="block">
                    <label>Upload Video</label>
                    <span class="youtube-input">
                        <input id="file" type="file" name="file" />
                    </span>                        
                </p>
                <input type="hidden" name="token" value="<?php echo( $response->token ); ?>"/>
                <input type="submit" value="Upload Video" />
            </form> <!-- /form -->
            
        <!-- Final Step -->
        <?php elseif( $unique_id != '' && $status = '200' ) : ?>        
        <div id="video-success">
            <h4>Video Successfully Uploaded!</h4>
            <p>Here is your url to view your video:<a href="http://www.youtube.com/watch?v=<?php echo $unique_id; ?>" target="_blank">http://www.youtube.com/watch?v=<?php echo $unique_id; ?></a></p>
        </div> <!-- /div#video-success -->
        <?php endif; ?>
        
    </body>

Basically, what we did above is to get our upload url $response->url and token and then send our video to that url. A status code 200 shows that our upload was successful.

<?xml version='1.0' encoding='UTF-8'?>
<response>
  <url>http://uploads.gdata.youtube.com/action/FormDataUpload/AEF3087AUD<url>
  <token>AEwbFAQEvf3xox...</token>
</response>

You need to add the nexturl parameter to the form’s target URL. This parameter specifies the URL to which YouTube will redirect the user’s browser when the user uploads his video file. After the video is uploaded in the browser, the user will be redirected to the nexturl URL

I have attached the full source code to this article for you to work with.

Comment below if you have any issues or questions.

“You must be either the copyright holder or the authorized representative of the copyright owner for all video files that you deliver to YouTube. Similarly, users who upload videos to YouTube from your site must be either the copyright holder or the authorized representative of the copyright owner for all videos that they upload.” – YouTube.

Resources

Download Source

I write codes... web, mobile, desktop and hack stuffs

Leave a Reply

Your email address will not be published. Required fields are marked *