Friday, 24 May 2019

How to download youtube video in PHP?

How to download youtube video in PHP?

Question: How to Get the YouTube Video Id?
Suppose we have following YouTube URL:
https://www.youtube.com/watch?v=iHp5veCNPVw
iHp5veCNPVw is YouTube Id.



Question: How to download YouTube using YouTube video Id?
$vid = 'iHp5veCNPVw'; //the youtube video ID
$vformat = 'video/mp4'; //video/mp4, video/webm, video/mp3 et.
$fileName = 'downloadvideos';//File name, downloadvideos.mp4
parse_str(file_get_contents("http://youtube.com/get_video_info?video_id=" . $vid), $info); //decode the data
$streams = $info['url_encoded_fmt_stream_map']; //the video's location info
$streams = explode(',', $streams);
foreach ($streams as $stream) {
    parse_str($stream, $data); //decode the stream
    if (stripos($data['type'], $vformat) !== false) { //We've found the right stream with the correct format
        $video = fopen($data['url'] . '&signature=' . @$data['sig'], 'r'); //the video
        $fullFileName = $fileName . '.' . str_replace('video/', '', $vformat);
        $file = fopen($fullFileName, 'w');
        stream_copy_to_stream($video, $file); //copy it to the file
        fclose($video);
        fclose($file);
        echo 'Downloaded Path:  ' . __DIR__ . '/' . $fullFileName;
        break;
    } else {
        echo "Unable to download this video.";
    }
}