Uploading a video to youtube through api version 3 in PHP

I’ve been trying to get the API from google youtube to work so I can upload video’s to it from my web application. It took me extremely long to figure out how the API worked because of lack of documentation at this moment. That is why I’m writing a blog post about it so people will hopefully have less trouble with it.

Downloading the Google PHP Library

First you need to get the Google PHP API Libary so not the Zend libary. As you can see that libary also has an example. Parts of that example we will use to handle the authentication for us.

Registering your Google API Client and Developer Keys

Now you need to register your client and developer keys. Registering your Client Key can be done at the Google Api Console. Here you can register your client key at “Client ID for web applications” and your developer key at “Simple API Access”. More information can be found at the Google PHP Client OAuth2 Docs

The PHP Code used to Upload a Video to Youtube

The following code is partly from google and Partly written by me trying to figgure out for the google version 3 api is working.

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_YouTubeService.php';

// Set your cached access token. Remember to replace $_SESSION with a real database or memcached.

// Connect to the Account you want to upload the video to (Note: When Remembering your access code you only need to do this once)
$client = new Google_Client();
$client->setApplicationName('Youtube PHP Starter Application');

// Load the Youtube Service Library
$youtube = new Google_YouTubeService($client);

// Authenticate the user when he comes back with the access code
if (isset($_GET['code']))
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));

// Check if the Token is set in the Session. If so set it to the client
if (isset($_SESSION['token']))

// Check if the client has an access Token elke Give him a login Link
if ($client->getAccessToken())
    // Upload the youtube Video
        $path_to_video_to_upload = '/set/the/direct/path/to/your/video.avi';

        // Get the Mimetype of your video
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($finfo, $path_to_video_to_upload);

        // Build the Needed Video Information
        $snippet = new Google_VideoSnippet();
        $snippet->setTitle('Title Of Video');
        $snippet->setDescription('Description Of Video');
        $snippet->setTags(array('Tag 1', 'Tag 2'));

        // Build the Needed video Status
        $status = new Google_VideoStatus();
        $status->setPrivacyStatus('private'); // or public, unlisted

        // Set the Video Info and Status in the Main Tag
        $video = new Google_Video();

        // Send the video to the Google Youtube API
        $created_file = $youtube->videos->insert('snippet,status', $video, array(
            'data' => file_get_contents($path_to_video_to_upload),
            'mimeType' => $mime_type,

        // Get the information of the uploaded video
    catch (Exception $ex)
        echo $ex;

    // We're not done yet. Remember to update the cached access token.
    // Remember to replace $_SESSION with a real database or memcached.
    $_SESSION['token'] = $client->getAccessToken();
    $authUrl = $client->createAuthUrl();
    print "<a href='$authUrl'>Connect Me!</a>";

That’s it. I hope you have enough information to get your youtube upload with API version 3 working like it should. If you have questions of some information is lacking feel free to request it in the comments section.

A list of the Category Id’s you can use

"id": "1",
"title": "Film & Animation"

"id": "2",
"title": "Autos & Vehicles"

"id": "10",
"title": "Music"

"id": "15",
"title": "Pets & Animals"

"id": "17",
"title": "Sports"

"id": "18",
"title": "Short Movies"

"id": "19",
"title": "Travel & Events"

"id": "20",
"title": "Gaming"

"id": "21",
"title": "Videoblogging"

"id": "22",
"title": "People & Blogs"

"id": "23",
"title": "Comedy"

"id": "24",
"title": "Entertainment"

"id": "25",
"title": "News & Politics"

"id": "26",
"title": "Howto & Style"

"id": "27",
"title": "Education"

"id": "28",
"title": "Science & Technology"

"id": "29",
"title": "Nonprofits & Activism"

// Start Movie Tags
"id": "30",
"title": "Movies"

"id": "31",
"title": "Anime/Animation"

"id": "32",
"title": "Action/Adventure"

"id": "33",
"title": "Classics"

"id": "34",
"title": "Comedy"

"id": "35",
"title": "Documentary"

"id": "36",
"title": "Drama"

"id": "37",
"title": "Family"

"id": "38",
"title": "Foreign"

"id": "39",
"title": "Horror"

"id": "40",
"title": "Sci-Fi/Fantasy"

"id": "41",
"title": "Thriller"

"id": "42",
"title": "Shorts"

"id": "43",
"title": "Shows"

"id": "44",
"title": "Trailers"
// End Movie Tags

Author: Robert Jan de Dreu

How to update mysql records from a select

While I was working on a project I needed to migrate some information from one table to the other. But only specific data. I was looking for a solution but I only found one easily for a mssql database. After some research I found a way to copy data from one to an other table while using where to filter:

UPDATE table1 tb1
INNER JOIN table2 tb2
ON tb1.id = tb2.sub_id
tb1.field = tb2.field
WHERE tb1.field = ''

With this query you can easily transfer data from table2 to table1

Push new project to an external bare git repository

Sometimes you need to start up your project. I never found a simple guide on how to push to a bare git repository so I’m writing this down as a note to myself.
git init
touch .gitignore
git add .gitignore
git commit -m "Initial commit"
git remote add origin /path/to/bare/repo
git push origin master

This will push your new changes to you external bare git repository

Install Redmine with automated git integration (Centos, Redhat)

I had a few days work on this one while it was supposed to be done in a hour. The problem? Lack of good documentation. There seems to be no complete tutorial on the Internet how to completely integrate git with Redmine so I figured to make one myself for you my dear reader but also a little bit for myself so I can easily find it back.

Good to know: I might have used yum but we all know that the repo’s of centos en redhad are way behind in version. Please make sure you have extra repo’s. I used:

Make sure you also use repo’s for a more updated ruby and gems. I’m going to start with the ruby install right from the bat. Please make sure your server has Apache and Mysql installed. This tutorial won’t explain that part.

Installing Ruby

Redmine works on ruby so we will start with installing ruby. You can install ruby in 2 ways.

  1. From the source
  2. Trough yum

Thoose the one you prefer I will use the yum method:
yum install ruby ruby-devel ruby-libs ruby-irb ruby-rdoc ruby-mysql

Just make sure that you have the right version of ruby. The standard repositories don’t have the later versions yet so make sure to use other repositories. I used version 1.8.5. Just make sure that you use a compatible version. You can see that here: Redmine Ruby Versions

Installing ruby-gems

Installing ruby-gems goes most of the time by hand:
wget http://rubyforge.org/frs/download.php/45905/rubygems-1.3.1.tgz
tar xvf rubygems-1.3.1.tgz
cd rubygems-1.3.1
ruby setup.rb

Installing Rails

You need to install rails trough gem. But you need to make sure you install the version that Redmine likes:
gem install rails -v=2.3.5

Installing Rack

gem install rack -v=1.0.1

Installing mongrel (optional)

You won’t need to install mongrel but it makes your site run so much faster so it is recommended you install it.
gem install mongrel

Installing Redmine

Download redmine

First lets download redmine. You can download the latest version at the Redmine site. Unpack it and put it in the folder you want. I will be using “/home/redmine/redmine” as my redmine root.

Creating the database

First we need to install the database. In this tutorial we will be using mysql as database driver since it’s commonly known. Log into your mysql console and run this:
create database redmine character set utf8;
create user ‘redmine’@'localhost’ identified by ‘my_password’;
grant all privileges on redmine.* to ‘redmine’@'localhost’;

Configuring Redmine

Let’s configure Redmine now. Fist we need to copy the Redmine configure file at the right place.
cd /home/redmine/redmine
cp  config/database.yml.example config/database.yml

Now edit the config to the settings you set the database with.
adapter: mysql
database: redmine
host: localhost
username: redmine
password: my_password

Generate a session store secret

cd /home/redmine/redmine
rake config/initializers/session_store.rb

rake generate_session_store

Create the database structure

RAILS_ENV=production rake db:migrate
RAILS_ENV=production rake redmine:load_default_data

Set the right permissions for the files

chown -R redmine:redmine files log tmp public/plugin_assets
chmod -R 755 files log tmp public/plugin_assets

Test Run redmine

ruby script/server webrick -p 3000 -e production

People note this is only for testrunning redmine. Don’t use it for production. Use one of the many other guides in the Redmine wiki to setup redmine to use either passenger (aka mod_rails) or mongrel to serve up your redmine.

Installing and automating Git

Now we will start automating all git processes with Redmine. This means when you make a new project it will automatically create a repository for it. Since there are already many tutorials how to do this with svn ours will be about git.

First create a directory where all git repositories will be in. Mine is located at: “/home/redmine/git_repositories”

Edit your apache

Now edit your httpd.conf to fit your settings:

PerlLoadModule Apache::Redmine

SetEnv GIT_PROJECT_ROOT /home/redmine/git_repositories/
ScriptAlias /git/ /usr/libexec/git-core/git-http-backend/
<Location /git>
	RedmineGitSmartHttp yes
	DAV on

	AuthType Basic
	Require valid-user
	AuthName "Git"

	PerlAccessHandler Apache::Authn::Redmine::access_handler
	PerlAuthenHandler Apache::Authn::Redmine::authen_handler

	RedmineDSN "DBI:mysql:database=redmine;host=localhost"
	RedmineDbUser "redmine"
	RedmineDbPass "my_password"

Alias /git-private /home/redmine/git_repositories

<Location /git-private>
	Order deny,allow
	Deny from all
		Options Indexes FollowSymLinks MultiViews
		Allow from
		Allow from localhost

Maybe you already noticed. That this is completely different from the configuration the Redmine sites gives. This is because we will be using git’s git-smart-http protocol. With this you can push your repository straight to the http link. If you are a valid user. For this to work you need to make sure you git version is higher than 1.6.6. Also check all paths for this httpd config since some could be off. Just try to locate the correct files with “find / -name yourfilenamehere”.

You will need to patch your Redmine.pm to support. this protocol. You can find the patch for Redmine.pm here: Redmine.pm Patch Note:please make sure this patch isn’t already committed else you might patch a already fixed file. Also use linux “patch” to patch the file.

If everything is working correctly you should be able to push to the httpd “IF” your repository exists and is setup the right way.

Setting up Auto creation and checking

Some people might want Redmine to auto create their repository when a new project is added and keep tracking the changes. For this you will need to add 2 lines to the cron:
*/1 * * * * root ruby /home/redmine/redmine/script/runner "Repository.fetch_changesets" -e production
*/1 * * * * root ruby /home/redmine/redmine/extra/svn/reposman.rb -s /home/redmine/git_repositories/ -r [external-redmine-link]:3000 -u /home/redmine/git_repositories --scm git -k [repository-key] -g redmine -o redmine --verbose >> /var/log/reposman.log

This should be all to get your redmine / git integration working if I missed something or if you get errors. Please comment. I will try to edit the tutorial and help you out where I can.

Author: Robert-Jan de Dreu

Porting a project from normal php to MVC

I’ve been working on a project for quite a while. It needed to be extended heavily. The designer before me had made his own kind of MVC system with smarty and OOP. Still the application had some huge structure and scaling issues. I’m going to talk about the process  of migrating an existing application to Kohana (or any other MVC framework).

Phase 1: Structuring / Designing

Finding the reason of the rewrite

Why are you going to rewrite the application. Just because MVC is so much better? If so you are wasting your boss his money. Migrations need to be thought trough. You could ask yourself the following questions to make sure you are making the right choice:

  • Will the migration make the application more flexible for extension?
  • Will it lessen the development time and money spend?
  • Is the application big enough to be written in MVC?
  • Doesn’t the application contain functions that will break when you migrate it.
  • (Do you have enough time / Is your boss patient enough) to rewrite your application.

If you answer these questions with a positive answer your application would be fit for migrations (note: This doesn’t mean you HAVE to migrate it).


Please think about structure and design

While some tend to start rewriting the application right off the bat, it’s better to think about what your MVC application would look like when you’re done. To to do this you will need to know what the current application consists of. Look at what code could be the controllers and how you are going to structure your views and models. You could make a chart with all object listed in a structured way.

Example 1: Structuring

This chart shows a way to structure your objects.

You could wonder why it’s important to think about structuring before you start the migration. Some of you may think: “I’ll just do it when I’m writing it”. This is wrong. You should always think about how you are going to structure your application before you are going to write it. What would be the use of MVC if you aren’t going to structure it correctly anyway.

Deciding what tools to use

Before you are going to run off and write code it’s important that you decide what libraries you are going to use. Like ORM, Auto Modeler standard Auth or Auth+ACL. These decisions need to be made before you start writing. If you find out that you need to switch in the middle you just burned a lot of time of your life and from your boss (I bet he won’t be happy about that).

When you research about what libraries you are going to use you also need to consider (and please document !!!) how you are going to use them and for what purpose you are going to use them. Most applications fall on non-existent planning and documentation. By ruling out any changes you will avoid these troubles.

Phase 2: Beginning migrating code

You now know what the application will look like when you’re done. Now we should start with the migration. While some may think otherwise there are multiple approaches of migrating an application. Both have their pro’s and con’s so it’s up to you how you’re going to tackle your migration.

Option 1: Full rewrite

This is the most time expensive way of migrating. You will check and rewrite most of the code. You can say the application will be completely different after this step. This method takes a lot of time but also gives the best quality code from the beginning. When writing for a boss or an external party you will have to explain that rewriting an application takes a lot of time and somehow they need to be satisfied with that answer.


  • Clean High quality Code
  • Good check for bugs and sometimes results in the fixing of many known bugs


  • Takes a lot of time
  • Needs a patient boss / client

Option 2: MRR (Migrate Release Rewrite)

This is the method I like best. This method is just a copy paste job while structuring your application and rewriting only the needed parts. Porting you application will take a small amount of time. When completely finished you will release it to the public. Your boss/client will like the fast response and release. After the release you will start the rewrite. Slowly you will look for bloated code and update it while releasing multiple version that patch the production environment. This way your client / boss will see that the application is being improved and worked on and be more satisfied with the results.


  • First release is fast.
  • Boss / Client doesn’t have to wait a long time for a release.


  • The first release still contains all the bugs that the old application has.
  • Past release rewrites could take a bit more time.

Phase 3. Releasing? Or not

Join the Dark side

At this point a lot of programmers tend to join the dark side (*coff coff*). They keep rewriting their sources and updating it without releasing it first. While I agree with the reasoning that the first release should be good your boss won’t. Even if the application is not completely done its best to release a early alpha/beta version. While not finished your users may find bugs that you won’t find.

Fixing filed bugs

While you are getting bug reports you start fixing the blocking bugs. Making small updates to the production environment and notifying users that the bug they found has been fixed (they even may start to think that you might be useful after all, and not lazy). The users can see that the application is moving forward while you are motivated to update it.

Phase 4. Rewrite

Bloated code

Rewriting applications might be a difficult and nerve-whacking job it’s still the one that is needed the most. Doesn’t it make you cry that you feel the need to post multiple snippets of source to theDailyWTF (that are all from the same application). Well by rewriting them we are going to make sure that won’t happen again and extending it will be a breeze (note to self: make sure your code doesn’t end up at theDailyWTF). Don’t just write code think it trough.

Questions to ask yourself

Some questions you might want to ask yourself when writing:

  • Am I going to use this variable more than once?
  • Why do I keep pushing ctrl+c?
  • Can’t I make this an independent function?
  • Should I put everything in one class?
  • Where does my validation go?
  • Where does my authorization go?
  • Where do my data + structuring go?
  • Can’t I just post trough a single variable?
  • What should or shouldn’t I do in my views

While I have a bigger list ;), these would be the main points interest.


It’s important that you have a clear view of the structuring that you will use for your application. If you don’t know how to structure your application talk to other developers. They can point you in the right direction. If you aren’t sure just ask for arguments and reasons why they choose for their approach. Some of them might have thought a lot about the problem you now facing and come to a conclusion that worked best for them.

Phase 5. Issues

Most likely this will be the most interesting part of this talk. When you plan and document  right, you shouldn’t run into any problems but it doesn’t completely prevent them. This part of the article will talk about the problems I ran into because of insufficient checking and testing.

Different behavior between production and development environment

This might be the most common issues around when migrating. While the previous application just ran fine and the new one doesn’t. Most likely the differences in the PHP or MySQL version causes this to occur but it could be something completely unexpected and hard to trace like differences in modules and configuration.

Finding out that you are doing it wrong when you are almost done

I really hate it when this occurs. When I find out that I was doing it completely wrong. And if I would change it, it would cost me a lot less time in the future. I tend to ignore this when it’s not blocking. I note it down in my bug tracker and finish and release the application. After releasing I start to rewrite it and delete all my quick fixes that I did before. Maybe a useful tip. I tend to add a comment to a quick fix, like:

//todo: Delete this quick fix after rewrite

When I comment it like this I can track down the bad code and update it fast.

When the issue is blocking(you can’t fix it without the rewrite) you don’t have much of a choice so just start rewriting (sorry no useful tips here).

Breaking stuff that once worked

This will happen to everyone. When migrating code stuff breaks. It happens because of missing libraries or functions that are positioned and loaded somewhere else. You can prevent this with testing everything what a user does within the application, checking the calculations and output it throws at you. Sometimes broken stuff doesn’t throw an error at you and could generate incorrect information that the user is counting on. Since the user things that even after the migration the values are correct it won’t doubt and double check them.

If this might occur anyway, patch the bug the same day so that it won’t influence any company processes.

Author: Robert-Jan de Dreu

CSS3 owns IE not

Lately I’ve been looking for nice simple fixes for common problems inside styling your application. I’ve began to notice that CSS3 implements a lot features that I was looking for, to find out later that Microsoft is being stubborn again to implement it right(if they do it at all).

Likely most web developers feel this but when you run your application in IE a little part inside of you dies. Since I don’t want to take the focus to Microsoft (I only make a exception if it’s bad for Microsoft’s sales) I’m going to continue with CSS3.

CSS3 has great new features that make your life of a web developer a lot easier. You almost could say that we’re getting spoiled don’t you think? I’m going to talk about 2 of the most popular functions:

1. Even and Odd Rows
2. Rounded Corners

Even and Odd Rows
Alway noticed that you had to make a script to be able to style even and odd Rows? I bet you did. I hated making it because it acctually was a tiny bit of useless(ugly) code inside your template. CSS3 will fix this for you. With CSS3 you just use the next CSS code and it will style your rows on odd or even count without having to code anything inside your template:

 tr:nth-child(even) { background: #CCCCCC; } tr:nth-child(odd) { background: #FFFFFF; } 

This tiny code makes your even rows grey and your odd rows white. Can’t be easier can it?

Rounded Corners
Back in the time we used images to make our corners round. At that time we didn’t have anything else. Now we can use “border-radius” a fix to this. By setting the amount of pixels we can make our corner more or less round:

-moz-border-radius: 6px; 
-webkit-border-radius: 6px; 
border: 1px #CCC solid;

This were the features of CSS3 I really liked. Lets hope they will be in all browsers soon. (or that everyone stops using IE 😉 )

Using Jquery serialize with php

When making forms ever had the urge to find something easier than having to define every value in your JavaScript? I did and found something nice called serialize. What is does is add all values into 1 string. Because I began to like serialize I’m writing an article on the use of it.

Lately I see a lot of people writing their own functions to deserialize it in php not knowing that php has it’s own function for deserializing namely ‘parse_str’. What it does is get the values and put them into an array so you can access them individually. Here is a little code for example:

This is the Template

<script type="text/javascript">
	function refresh(data) {
			var search = $("#searchform").serialize();
			var url = 'search.php'; 

			$.post(url, search, refresh, "html"); 
<form id="searchform">
		<td><input type="text" name="name" size="30" /></td>
		<td><input type="text" name="surname" size="30" /></td>
		<td>E-mail address:</td>
		<td><input type="text" name="email" size="30" /></td>
<input id="search" type="button" value="Search" />

This is the php handler (search.php)

<?php //Unserialize string to array 
$searchserialized = $_POST['search']; 
parse_str($searchserialized, $searcharray); 

$name = $searcharray['name']; 
$surname = $searcharray['surname']; 
$email = $searcharray['email']; 

echo $name.'-'.$surname.'-'.$email;

Man it’s so easy to use serialize

Author: Robert-Jan de Dreu

Dropdowns in Kohana

I began to get irritated that I always had write a foreach for the Dropdowns after the query. So I was thinking isn’t there a more easier way to do it. First I wrote a helper to do it for me but It was clumsy in my opinion. Since I like nice clean applications I extended the Database_Driver class. The problem is that you need too add it directly to system because you can’t write it in app.

Therefore you will need to add the following code in “\system\libraries\drivers\Database.php”:

 public function select_list($id, $descriptor) { $array = array(); $result = $this; foreach ($result as $key=>$value) { $array[$value->$id] = $value->$descriptor; } return $array; } 

After you did this you can use it like this:

 $user_model = new User_Model; $users = $user_model->read_users()->select_list('user_id', 'user_name'); print form::dropdown('users', $users); 

Using Smarty in Kohana

Oh god why would you use smarty in kohana!! I know it’s bad. My boss wants me to use smarty in kohana so I’m granting his wish. Still I don’t like doing it. Anyway while I’m at it why not use my time to write a article on how to use it.

A person with the nick d9 made a nice implementation of Kohana with Smarty using the normal template methods. So no writing smarty assigns in your controller wohoo!!

I uploaded it to my own server for bandwidth sake so here it is:


Well back to basics.  Lets first write the model that gets some values from the database. Since you all can guess how the database will look I’m not going to post a query script.

The model (user.php):

As you can see its the same as the standard models of kohana nothing different on it.

In the controller we will do 1 thing a bit different but other than that it will be the same (user.php):

read_users(); //smarty way $users = $user_model->read_users()->result(FALSE); $this->view = new View('user/index'); $this->view->users = $users; $this->template->content = $this->view; } }

I posted how I would do it normally and how I do it with smarty next to each other. As you can see a rule is added namely “result(FALSE)” because of this the result will be returned as a array in place of a object so that smarty can parse trough it. Also a comment on the Global_Controller I extend that is just a controller that contains my database connection and the global template namely “$template”.

Now as last lets show you the template namely (user/index.tpl) and see how smarty goes in its work:

{foreach from=$users key="k" item="report"} {/foreach}
ID Name Address City
{$report.id} {$report.name} {$report.address} {$report.city}

That is all you need to know. Easy isn’t it? Btw I still hate smarty implementations in kohana but it works.

Someone also released a smarty plugin for kohana3 look here: https://github.com/MrAnchovy/kohana-module-smarty/wiki

Using the short if statement

I’m always lost when I need to find the shorthand version of the if statement in php. That is why I write again a small note for myself so I can find it again.

$value = 'sunny'; 
$weather = ($value == 'sunny') 
    ? "It is a sunny day"
    : "Stay in bed its raining"; 

echo $weather;

There are multiple implementations for the short tag but this is the one I use the most. Maybe I document others too when I feel like it.