A Simple YouTube Video Downloader Script in PHP

YouTube is the most popular video sharing platform in the world. It helps users to upload, view, and share videos that keeps  community guidelines. Tons of people selected YouTube video making as full job, as they create and upload videos and getting revenue from YouTube Adsense( Google Adsense). But, YouTube lacks one important feature, direct download of videos to users computers or mobiles. That’s why we created this  tutorial,   and we will show how to download YouTube video using PHP. This YouTube downloader php script 2020 helps you to download 90% of Youtube videos from Youtube.

First things first, we have below scripts to work YouTube downloader.

  1. index.php
  2. class.youtube.php
  3. downloader.php

First we will examine the class.youtube.php as this is the core file executes important features for downloading a video from YouTube.

  • getYouTubeCode – Get the YouTube code from a video URL
  • processVideo – Process the video url and return details of the video
<?php
/**
 * Tutsplanet
 *
 * This class narrates the functions to support download a video from YouTube
 * @class YouTubeDownloader
 * @author Tutsplanet
 *
 */

Class YouTubeDownloader {

    /**
     * Get the YouTube code from a video URL
     * @param $url
     * @return mixed
     */
    public function getYouTubeCode($url) {
        parse_str( parse_url( $url, PHP_URL_QUERY ), $vars );
        return $vars['v'];
    }

    /**
     * Process the video url and return details of the video
     * @param $vid
     * @return array|void
     */

    public function processVideo($vid) {
        parse_str(file_get_contents("https://youtube.com/get_video_info?video_id=".$vid),$info);


        $playabilityJson = json_decode($info['player_response']);
        $formats = $playabilityJson->streamingData->formats;
        $adaptiveFormats = $playabilityJson->streamingData->adaptiveFormats;

        //Checking playable or not
        $IsPlayable = $playabilityJson->playabilityStatus->status;

        //writing to log file
        if(strtolower($IsPlayable) != 'ok') {
            $log = date("c")." ".$info['player_response']."\n";
            file_put_contents('./video.log', $log, FILE_APPEND);
        }

        $result = array();

        if(!empty($info) && $info['status'] == 'ok' && strtolower($IsPlayable) == 'ok') {
            $i=0;
            foreach($adaptiveFormats as $stream) {

                $streamUrl = $stream->url;
                $type = explode(";", $stream->mimeType);

                $qualityLabel='';
                if(!empty($stream->qualityLabel)) {
                    $qualityLabel = $stream->qualityLabel;
                }

                $videoOptions[$i]['link'] = $streamUrl;
                $videoOptions[$i]['type'] = $type[0];
                $videoOptions[$i]['quality'] = $qualityLabel;
                $i++;
            }
            $j=0;
            foreach($formats as $stream) {

                $streamUrl = $stream->url;
                $type = explode(";", $stream->mimeType);

                $qualityLabel='';
                if(!empty($stream->qualityLabel)) {
                    $qualityLabel = $stream->qualityLabel;
                }

                $videoOptionsOrg[$j]['link'] = $streamUrl;
                $videoOptionsOrg[$j]['type'] = $type[0];
                $videoOptionsOrg[$j]['quality'] = $qualityLabel;
                $j++;
            }
            $result['videos'] = array(
                'info'=>$info,
                'adapativeFormats'=>$videoOptions,
                'formats'=>$videoOptionsOrg
            );
            
            
            return $result;
        }
        else {
            return;
        }
    }

}

In processVideo() function, first we parse the outputs from the YouTube video info page. It is important to note that, chunks of data returning from this line of code, but we will not use all of this. Next, we check the status to see if its ok, then move to next steps of parsing the different streams by using this code $playabilityJson->streamingData->adaptiveFormats.

It returns different versions of  YouTube video such as mp4, mp3 and most importantly various qualities(720p,360p). Finally, we push all these to an array and set the value in return.

Download the YouTube video by using a simple form in PHP

We use the below form to take users input ie. YouTube video url. This comes in the index.php.

<form method="post" action="" class="formSmall">
	<div class="row">
		<div class="col-lg-12">
			<h7 class="text-align"> Download YouTube Video</h7>
		</div>
		<div class="col-lg-12">
			<div class="input-group">
				<input type="text" class="form-control" name="video_link" placeholder="Paste link.. e.g. https://www.youtube.com/watch?v=OK_JCtrrv-c">
				<span class="input-group-btn">
				<button type="submit" name="submit" id="submit" class="btn btn-primary">Go!</button>
			  </span>
			</div><!-- /input-group -->
		</div>
	</div><!-- .row -->
</form>

Next, we have to write our PHP code that inputs the video ID and return the different video urls for download.

<?php
require_once "class.youtube.php";
$yt  = new YouTubeDownloader();
$downloadLinks ='';
$error='';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $videoLink = $_POST['video_link'];
    if(!empty($videoLink)) {
        $vid = $yt->getYouTubeCode($videoLink);
        if($vid) {
            $result = $yt->processVideo($vid);
            
            if($result) {
                //print_r($result);
                $info = $result['videos']['info'];
                $formats = $result['videos']['formats'];
                $adapativeFormats = $result['videos']['adapativeFormats'];

                

                $videoInfo = json_decode($info['player_response']);

                $title = $videoInfo->videoDetails->title;
                $thumbnail = $videoInfo->videoDetails->thumbnail->thumbnails{0}->url;
            }
            else {
                $error = "Something went wrong";
            }

        }
    }
    else {
        $error = "Please enter a YouTube video URL";
    }
}
?>

Above script, we include the class fileclass.youtube.php , which is the core of this application. Finally, we confirms the POST method and fetch the results from the class methods.

The below code will show you how to display the YouTube download links in a tabular format, with quality and type.

<?php if($formats):?>
        <div class="row formSmall">
            <div class="col-lg-3">
                <img src="<?php print $thumbnail?>">
            </div>
            <div class="col-lg-9">
                <?php print $title?>
            </div>
        </div>

        <div class="card formSmall">
            <div class="card-header">
                <strong>With Video & Sound</strong>
            </div>
            <div class="card-body">
                <table class="table ">
                    <tr>
                        <td>Type</td>
                        <td>Quality</td>
                        <td>Download</td>
                    </tr>
                    <?php foreach ($formats as $video) :?>
                        <tr>
                            <td><?php print $video['type']?></td>
                            <td><?php print $video['quality']?></td>
                            <td><a href="downloader.php?link=<?php print urlencode($video['link'])?>&title=<?php print urlencode($title)?>&type=<?php print urlencode($video['type'])?>">Download</a> </td>
                        </tr>
                    <?php endforeach;?>
                </table>
            </div>
        </div>

        <div class="card formSmall">
            <div class="card-header">
                <strong>Videos video only/ Audios audio only</strong>
            </div>
            <div class="card-body">
                <table class="table ">
                    <tr>
                        <td>Type</td>
                        <td>Quality</td>
                        <td>Download</td>
                    </tr>
                    <?php foreach ($adapativeFormats as $video) :?>
                        <tr>
                            <td><?php print $video['type']?></td>
                            <td><?php print $video['quality']?></td>
                            <td><a href="downloader.php?link=<?php print urlencode($video['link'])?>&title=<?php print urlencode($title)?>&type=<?php print urlencode($video['type'])?>">Download</a> </td>
                        </tr>
                    <?php endforeach;?>
                </table>
            </div>
        </div>
        <?php endif;?>

How to download the video using the link?

You may have noticed there is page called downloader.php in the above script. This script is responsible for the force download of the file to your computer or mobile. This is standard force download process in PHP.

<?php
$downloadURL = urldecode($_GET['link']);
//print  $downloadURL;exit;
$type = urldecode($_GET['type']);
$title = urldecode($_GET['title']);

//Finding file extension from the mime type
$typeArr = explode("/",$type);
$extension = $typeArr[1];

$fileName = $title.'.'.$extension;


if (!empty($downloadURL)) {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header("Content-Transfer-Encoding: binary");

    readfile($downloadURL);

}

I hope everyone enjoyed this article, don’t forget to share this article with your peers.

You can download this source code from GitHub RepoYouTube Downloader Source Code

UPDATE(20 Aug 2020)

The adaptive formats in YouTube provides videos with video only and audios with audio only options. But we have updated the script with another two other formats that’s available with both audio and video.  The only solution to work with different quality is to merge audio and video from adaptive formats.  We are not going very deep with ffmpg, but you may install and play with this cross-platform solution to record, convert and stream audio and video.

A sample command would be

ffmpeg -i videoplayback.mp4 -i videoplayback.m4a -c:v copy -c:a copy output

Leave a Comment

Your email address will not be published. Required fields are marked *

Hire a server Expert to resolve the issue Now.

Hire a server Expert to resolve the issue Now.

Resolve this issue in just 5$ from https://serverexpert.io

 

You have Successfully Subscribed!

Open chat