Download videos from Youtube using PHP and API

in PHP, PHP Code / 17 Comments

Hi friends, In the earlier we learned how to download a file using php code, this post is explains how to download videos from Youtube using by PHP code and API. This post by Siddhu Vydyabhushana, his earlier post is jQuery plugin for Text to Speech, this time come with this unique post.

Download videos from Youtube using PHP and API by Siddhu Vydyabhushana

Download videos from Youtube using PHP and API by Siddhu Vydyabhushana

demo link for download videos from Youtube using PHP and API download link for Download videos from Youtube using PHP and API

Main file which is used for downloading video

PHP Code

<head>
<link rel="stylesheet" href="style.css" />
<title>Download and save any video from Youtube,Dailymotion,Metacafe, more!</title>
<meta name="description" content="Download and save videos directly from Youtube, Google, Metacafe, Putfile and more. Simply copy and paste.">
<meta name="keywords" content="online,3gp,mp4,flv,avi,keepvid,keep,vid,siddhu,download,direct,help,rip,copy,save,video,stream,youtube,">
<meta name="robots" content="All,index,follow"><meta name="revisit-after" content="7 days">
</head>
<center>
by <a href="http://facebook.com/siddhusce" >Siddhu vydyabhushana</a>
<table>
<tr>
<td>
<form method="post">
<label style="color:#333333"><h3>3GP,FLV,MP4,AVI and more...(***No JAVA Plugins Required***)</h3></label>
<label style="color:#ff3377"><h1>Paste <b style="color:#eeeeee;background:#3399ff">YOUTUBE</b> link here to download:</h1></label>
<input type="text" name="url" value="" style="width:500px;height:30px" placeholder="Enter link here to download :http://www.youtube.com/watch?v=YeR7McJIltk">
<input type="submit" style="background:#3399ff;height:30px;color:white" value="Get Video Link">
</form>
</td>
</tr>
</table>
</center>
<hr color="#33bbee">
<?php
if(isset($_POST['url']))
{
  include('curl1.php');
  include('curl.php');
  include('youtube.php');
  $tube = new youtube();
  $links = $tube->get($_POST['url']);
  if($links) { ?>
    <center>
    <h2>Downloadable Links:</h2>
    <?php
    $url=$_POST['url'];
    $url=substr($url,31);
    $my_video_info = 'http://www.youtube.com/get_video_info?&video_id='. $url;
    $my_video_info = curlGet($my_video_info);
    $thumbnail_url = $title = $url_encoded_fmt_stream_map = $type = '';
    parse_str($my_video_info);
    echo '<h2 style="color:#3399ff">'.$title.'</h2>';
    echo '<p><img src="'. $thumbnail_url .'" border="0" hspace="2" vspace="2"></p>';
    $my_title = $title;
         for($i=0;$i<count($links);$i++)
       {
       ?>
<!--<a href='<?php echo $links[$i]['url'];?>'>Download <b><a>-->
<?php echo strtoupper($links[$i]['ext']);?></b><?php echo $links[$i]['type'];?>:
<?php
echo  '<a href="download.php?mime=' . $links[$i]['type'] .'&title='. urlencode($my_title) .'&token=' . base64_encode($links[$i]['url']).'" >download</a>';
?><br/><br/>

         <?php
       }
    ?>

    </center>
    </pre>
 
  <?php } else {

      echo $tube->error;

  }

}

?>

Code for curl1.php

<?php
class Curl {
    var $callback = false;
    var $secure = false;
    var $conn = false;
    var $cookiefile =false;
    var $header = false;
    var $cookie = false;
    var $follow = true;
   

    function Curl($u = false) {
        $this->conn = curl_init();
        if (!$u) {
            $u = rand(0,100000);
        }

        //$this->cookiefile= APP_PATH.'/cache/'.md5($u);
    }

    function setCallback($func_name) {
        $this->callback = $func_name;
    }

    function close() {
        curl_close($this->conn);
        if (is_file($this->cookiefile)) {
            unlink($this->cookiefile);
        }

    }

    function doRequest($method, $url, $vars) {

        $ch = $this->conn;

        $user_agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";

        curl_setopt($ch, CURLOPT_URL, $url);
        if ($this->header) {
            curl_setopt($ch, CURLOPT_HEADER, 1);
        } else {
            curl_setopt($ch, CURLOPT_HEADER, 0);
        }
        curl_setopt($ch, CURLOPT_USERAGENT,$user_agent);



        if($this->secure) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        }
       
        if ($this->cookie)
        {
            curl_setopt($ch, CURLOPT_COOKIE,$this->cookie);
        }

        if ($this->follow) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        } else {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookiefile);

        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: ')); // lighttpd fix
        }

        $data = curl_exec($ch);



        if ($data) {
            if ($this->callback)
            {
                $callback = $this->callback;
                $this->callback = false;
                return call_user_func($callback, $data);
            } else {
                return $data;
            }
        } else {
            return false;
        }
    }

    function get($url) {
        return $this->doRequest('GET', $url, 'NULL');
    }

    function getError()
    {
        return curl_error($ch);
    }

    function post($url, $params = false) {

        $post_data = '';

        if (is_array($params)) {

            foreach($params as $var=>$val) {
                if(!empty($post_data))$post_data.='&';
                $post_data.= $var.'='.urlencode($val);
            }

        } else {
            $post_data = $params;
        }

        return $this->doRequest('POST', $url, $post_data);
    }
}

function getPage($url,$post = false,$cookie = false)
{
    $pURL = parse_url($url);    
       
    $curl = new Curl($pURL['host']);
                   
    if (strstr($url,'https://'))
    {
        $curl->secure = true;  
    }
   
    if ($post) {
        return $curl->post($url,$post);
    } else {
        return $curl->get($url);
    }
   
}

Code for curl.php

<?php
function curlGet($URL) {
    $ch = curl_init();
    $timeout = 3;
    curl_setopt( $ch , CURLOPT_URL , $URL );
    curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
    curl_setopt( $ch , CURLOPT_CONNECTTIMEOUT , $timeout );
    /* if you want to force to ipv6, uncomment the following line */
    //curl_setopt( $ch , CURLOPT_IPRESOLVE , 'CURLOPT_IPRESOLVE_V6');
    $tmp = curl_exec( $ch );
    curl_close( $ch );
    return $tmp;
}  

/*
 * function to use cUrl to get the headers of the file
 */

function get_location($url) {
    $my_ch = curl_init();
    curl_setopt($my_ch, CURLOPT_URL,$url);
    curl_setopt($my_ch, CURLOPT_HEADER,         true);
    curl_setopt($my_ch, CURLOPT_NOBODY,         true);
    curl_setopt($my_ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($my_ch, CURLOPT_TIMEOUT,        10);
    $r = curl_exec($my_ch);
     foreach(explode("\n", $r) as $header) {
        if(strpos($header, 'Location: ') === 0) {
            return trim(substr($header,10));
        }
     }
    return '';
}

function get_size($url) {
    $my_ch = curl_init();
    curl_setopt($my_ch, CURLOPT_URL,$url);
    curl_setopt($my_ch, CURLOPT_HEADER,         true);
    curl_setopt($my_ch, CURLOPT_NOBODY,         true);
    curl_setopt($my_ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($my_ch, CURLOPT_TIMEOUT,        10);
    $r = curl_exec($my_ch);
     foreach(explode("\n", $r) as $header) {
        if(strpos($header, 'Content-Length:') === 0) {
            return trim(substr($header,16));
        }
     }
    return '';
}

function get_description($url) {
    $fullpage = curlGet($url);
    $dom = new DOMDocument();
    @$dom->loadHTML($fullpage);
    $xpath = new DOMXPath($dom);
    $tags = $xpath->query('//div[@class="info-description-body"]');
    foreach ($tags as $tag) {
        $my_description .= (trim($tag->nodeValue));
    }  
   
    return utf8_decode($my_description);
}
?>

Code for youtube.php

<?php
class youtube {
   
    var $conn = false;
    //gmail username
    var $username = "USERNAME";
    //gmail password
    var $password = "PASSWORD";
    var $error = false;
         
    function get($url)
    {
        $this->conn = new Curl('youtube');
       
        $html = $this->conn->get($url);

        if(strstr($html,'verify-age-thumb'))
        {
            $this->error = "Adult Video Detected";
            return false;
        }

        if(strstr($html,'das_captcha'))
        {
            $this->error = "Captcah Found please run on diffrent server";
            return false;
        }

        if(!preg_match('/stream_map=(.[^&]*?)&/i',$html,$match))
        {
            $this->error = "Error Locating Downlod URL's";
            return false;
        }

        if(!preg_match('/stream_map=(.[^&]*?)(?:\\\\|&)/i',$html,$match))
        {
            return false;
        }

        $fmt_url =  urldecode($match[1]);
   
        $urls = explode(',',$fmt_url);
               
        $foundArray = array();

        foreach($urls as $url)
        {            
            if(preg_match('/itag=([0-9]+)/',$url,$tm) && preg_match('/sig=(.*?)&/', $url , $si) && preg_match('/url=(.*?)&/', $url , $um))
            {
                $u = urldecode($um[1]);
                $foundArray[$tm[1]] = $u.'&signature='.$si[1];
            }
        }
                       
        $typeMap = array();

        $typeMap[13] = array("13", "3GP", "Low Quality - 176x144");
        $typeMap[17] = array("17", "3GP", "Medium Quality - 176x144");
        $typeMap[36] = array("36", "3GP", "High Quality - 320x240");
        $typeMap[5]  = array("5", "FLV", "Low Quality - 400x226");
        $typeMap[6]  = array("6", "FLV", "Medium Quality - 640x360");
        $typeMap[34] = array("34", "FLV", "Medium Quality - 640x360");
        $typeMap[35] = array("35", "FLV", "High Quality - 854x480");
        $typeMap[43] = array("43", "WEBM", "Low Quality - 640x360");
        $typeMap[44] = array("44", "WEBM", "Medium Quality - 854x480");
        $typeMap[45] = array("45", "WEBM", "High Quality - 1280x720");
        $typeMap[18] = array("18", "MP4", "Medium Quality - 480x360");
        $typeMap[22] = array("22", "MP4", "High Quality - 1280x720");
        $typeMap[37] = array("37", "MP4", "High Quality - 1920x1080");
        $typeMap[33] = array("38", "MP4", "High Quality - 4096x230");

       
        $videos = array();
       
        foreach($typeMap as $format => $meta) {
            if (isset($foundArray[$format])) {
                $videos[] = array('ext' => strtolower($meta[1]) , 'type' => $meta[2], 'url' => $foundArray[$format]);
            }
        }

        return $videos;

       
    }
   
}

Final Output of this Application will be

Download videos from Youtube using PHP and API by Siddhu Vydyabhushana

Download videos from Youtube using PHP and API by Siddhu Vydyabhushana

Studying Btech, Java addicted, web application developer,blogger Done 15+ projects

  1. Kathir

    Youtube video download script is not working in your demo. Please check it and update it.

  2. deepu

    Hi this script is working fine on your server.Could you please zip those files so that i can test on my server.I have copy pasted the above code but script is not working.

  3. vamsi

    Download.php is missing can u please send me?

    waiting for that..

    please send me whole working folder please

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>