Saturday, March 15, 2008

Perl/Php code to download youtube video


Share at Facebook

Youtube gets millions of video uploaded each days on their server. There are lots of websites that provides the direct download link for youtube video. Also lots of tools are available that are only developed to download youtube video as FLV format. Even more, Few later version of software like media player, quick player, or a download manager are allowing the facility to download the video from youtube.

There are few common methods to download a video from youtube. They all are using their own technique which is suitable for them to download the video. Now I'm telling you one of the most easiest way to download. It will help you to write a downloader your own if you are a coder. If you are a viewer, it will help you to download the desired video from youtube on your pc.

1) The video you want to download, just open it on your browser. View the source code. To view source code, just right click on the page and click view source or view page source depending upon your browser.
2) Now search the word "fullscreenUrl" on the source code. To search press Ctrl+F and write the keyword.
3) It will bring you a location where you find the code chunk as below image.



4) Copy all the text portion inside the single quote. I mean var fullscreenUrl = '<-- Copy all you see here -->'
5) Paste it to a notepad. and replace /watch_fullscreen with http://youtube.com/get_video.php
6) This is the download link for your youtube video. Open a browser and paste the link. Thats all.

For those who are coder, for them below is the PHP code that will generate the download link. Just pass the video page url to the below function.

function get_youtube_download_link($video_url){
   $html = file_get_contents($video_url);
   if(preg_match("/var fullscreenUrl = '(.*?)';/",$html,$match)){
      $download_url = $match[1];
      $download_url = preg_replace('/\/watch_fullscreen/',"http://youtube.com/get_video.php",$download_url);
      return $download_url;
   }
}

And below is the function written using Perl for those who loves perl. Just pass the youtube video video url to get the download link.

sub get_youtube_download_link{
   my $url = shift;
   use LWP::UserAgent;
   my $ua = LWP::UserAgent->new;
   $ua->agent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/2006120418 Firefox/2.0.0.1');
   my $req = HTTP::Request->new(GET => $url);
   $req->content_type('application/x-www-form-urlencoded');
   my $res = $ua->request($req);
   my $html = $res->content();
   if($html =~ /var fullscreenUrl = '(.*?)';/){
      my $download_link = $1;
      $download_link =~ s/\/watch_fullscreen/http:\/\/youtube.com\/get_video.php/;
      return $download_link;
   }
}




2 comments:

Lee said...

hi, thanks a lot for the codes! it's really helpful.

Xmddr said...

Nice tutorial, and thanks for the code!