Create a YouTube video downloader in PHP

YouTube is the most popular video sharing platform and videos is watched online. However, sometimes we have a need to get the video for offline uses or you don’t want the watermark of YouTube on the video or even you want to use YouTube as a free video host and YouTube didn’t provide any ways to get the raw video. So in this post, I’m teach you how to do it in PHP (so you can embed the video easily in your website).

By reverse engineering the YouTube embed player, we know that the player will issue a HTTP request to http://youtube.com/get_video_id?video_id=THE_VIDEO_ID to get information about a specific video. The result of the request contains a URL-encoded string that has the video’s location. So, we need to get that part first.

<?php
$id = $_GET['id']; //the youtube video ID
$format = $_GET['fmt']; //the MIME type of the video. e.g. video/mp4, video/webm, etc.
parse_str(file_get_contents("http://youtube.com/get_video_info?video_id=".$id),$info); //decode the data
$streams = $info['url_encoded_fmt_stream_map']; //the video's location info

The stream is also different sets of URL-encoded data separated by a comma. In order to retrieve all the streams, we need to turn it into an array by using explode(',',$streams).

$streams = explode(',',$streams);

After that, we need to loop through all the streams. Now it goes to the main part: select an appropriate stream and get its data.

foreach($streams as $stream){
    parse_str($stream,$data); //decode the stream
    if(stripos($data['type'],$format) !== false){ //We've found the right stream with the correct format
        $video = fopen($data['url'].'&signature='.$data['sig'],'r'); //the video
        $file = fopen('video.'.str_replace($format,'video/',''),'w');
        stream_copy_to_stream($video,$file); //copy it to the file
        fclose($video);
        fclose($file);
        echo 'Download finished! Check the file.';
        break;
    }
}

The script is finished. Now you can call it like this after you’ve put it to the server:

http://localhost/THE SCRIPT NAME.php?id=THE YOUTUBE VIDEO ID&fmt=THE MIME TYPE OF THE VIDEO

It can be turned into a streaming script that streams YouTube videos to the client also. Happy downloading YouTube videos!