Youtube Downloader using PHP

This short tutorial will show you how to download videos from Youtube using PHP. CURL is needed for this script because many webhosting now prohibit remote_fopen.

First function, get HTML content from an URL:< ?php
function get_content_of_url($url){
$ohyeah = curl_init();
curl_setopt($ohyeah, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ohyeah, CURLOPT_URL, $url);
$data = curl_exec($ohyeah);
curl_close($ohyeah);
return $data;
}
?>

Second function, get string that contain the clue of where the video file is located:< ?php
function get_flv_link($string) {
if (eregi("watch_fullscreen?video_id=(.*)&title=", $string, $out)) {
$outdata = $out[1];
}
return 'http://youtube.com/get_video.php?video_id='.$outdata;
}
?>

Next function, “visit” the link that we got from second function above. We will read the header and find out the real file location:< ?php
function get_http_header($url){
$uh = curl_init();
curl_setopt($uh, CURLOPT_URL, $url);
curl_setopt($uh, CURLOPT_HEADER, 1);
curl_setopt($uh, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($uh);
curl_close($uh);
return $res;
}
?>

Function above will return a bunch of HTTP headers and we don’t need them all. This function will parse the HTTP headers and only return the video location:< ?php
function show_url($http_header){
$arai = explode("n",$http_header);
foreach($arai as $ini){
if(eregi("location",$ini)) $url = $ini;
}
list($sampah,$hasil) = explode("Location:",$url);
return str_replace("n","",trim($hasil));
}
?>

Last thing to do, is bundle all functions above:< ?php
function download_youtube($url){
$data = get_content_of_url($url);
$next_url = get_flv_link($data);
$data = get_http_header($next_url);
return show_url($data);
}
?>

Wait, how to use the youtube downloader? It’s very simple:< ?php
$url = "http://youtube.com/watch?v=SAQZ0BDXn48";
echo download_youtube($url);
?>

That’s all folks. It’s a very interesting and chalenging moment when I wrote any kind of grabbing scripts. Hope it helps yo all.

In

4 responses

  1. siborjong Avatar
    siborjong

    bro aku ga bisa download source codenya. tolong di upload lagi dunk source codenya atau kirim ke emailku.sorry ya merepotkan 🙂

  2. Matt Avatar

    Hello. I pasted the code together however I can’t get it to run. Do you have the full source code available for me to look at?

  3. Vivek Thomas Avatar
    Vivek Thomas

    Hey

    Do you have a similar script for Google Videos. I tried altering your above code but was not that successful.

    So if you have a working Google Video Downloader please let me know.

    Thank you very much.

  4. Mark Avatar

    Code is not working. Have you came up with a fix yet?

Leave a Reply

Verified by MonsterInsights