How to download youtube videos using PHP script

  •  
  •  
  •  
  •  
  •  
  •  

Hi friends, you all know that Youtube is the most popular video sharing website where you can view, upload and share the videos online, but you can not download the videos for offline uses. However, if you want to see these videos offline you have to download them first, but how? Also, you may want to add some new features to your website like youtube video downloader. So friends, in this tutorial, I will guide you step by step on how to download youtube videos using PHP script.

How to download youtube videos using PHP script

Download Youtube Videos using PHP Script

The following PHP script accepts any kind of youtube video link and returns you the all available video formats with quality, size information. Then you can choose and download from them. Let’s proceed to the code —

index.php

<div class="container">
    <form method="post" action="">
        <div class="row">   
            <div class="col-lg-12">
                <h1 class="demo-page-header">-------    Download youtube video from the youtube link    -------</h1>
            </div>         
            <div class="col-lg-12">                    
                <div class="input-group">
                  <input type="text" class="form-control" name="video_link" placeholder="Paste link here.. e.g. https://www.youtube.com/watch?v=ie_atoiaEN4">
                  <span class="input-group-btn">
                    <button type="submit" name="submit" id="submit" class="btn btn-default" type="button">Go!</button>
                  </span>
                </div><!-- /input-group -->
            </div>            
        </div><!-- .row -->
    </form>
</div>

This is the simple HTML form which takes Youtube video link as input.

index.php

<?php
        //Download youtube videos using PHP script
        include("functions.php");
        if(isset($_POST['submit'])) {
            $video_link = trim($_POST['video_link']);
            if($video_link != "") {
                $video_id = "";
                $video_id_arr = getVideoId($video_link);
                if(sizeof($video_id_arr) == 3) $video_id = $video_id_arr[2];
                if($video_id != "") {
                    parse_str(file_get_contents("https://youtube.com/get_video_info?video_id=".$video_id),$info);

                    if(!empty($info) && $info['status'] == 'ok') {
                        $streams = $info['url_encoded_fmt_stream_map']; //the video's location info
                        $streams = explode(',',$streams);
                        $video_title = $info['title'];
                        ?>
                        <div class="row margin-top-bottom">
                            <div class="col-md-12 text-center">
                                <img class="img-responsive " src="<?php echo $info['thumbnail_url']; ?>">
                                <label class="video_title"><?php echo $video_title; ?></label>
                            </div>                                                        
                        </div>
                        
                        <div class="row">
                            <div class="col-xs-12 col-md-12">
                                <table class="table table-striped">
                                    <thead>
                                      <tr>
                                        <th>Quality</th>
                                        <th>Format</th>
                                        <th>Size</th>
                                        <th>Action</th>
                                      </tr>
                                    </thead>
                                    <?php
                                    foreach($streams as $stream) {
                                        parse_str($stream, $data); //decode the stream
                        
                                        $formated_size = getRemoteFilesize($data['url']);
                                        $size_in_bytes = getRemoteFilesize($data['url'], false);

                                        $video_type = explode(";", $data['type']);
                                        $ext  = str_replace(array('/', 'x-'), '', strstr($video_type[0], '/'));
                                        ?>
                                        <tr>
                                            <td><?php echo $data['quality']; ?></td>
                                            <td><?php echo $ext; ?></td>
                                            <td><?php ($formated_size != "-1" ? print $formated_size : print "---") ?></td>
                                            <td><a href="download.php?url=<?php echo base64_encode($data['url']);?>&title=<?php echo $video_title; ?>&mime=<?php echo $video_type[0]; ?>&ext=<?php echo $ext; ?>&size=<?php echo $size_in_bytes; ?>" target="_blank">Download</a>
                                            </td>
                                        </tr>
                                    <?php                                    
                                    } 
                                    ?>
                                </table>
                            </div>
                        </div>
                    <?php
                    } else {
                        echo "<h4 class='error'>Something wrong! Please try again.</h4>";
                    }
                } else {
                    echo "<h4 class='error'>Invalid video link!</h4>";
                }
            }
        }
        ?>

In the above code, at first, we received the video link and extract the video id from it. After getting the video id we will download the information about the video using file_get_content() method and then parse the query strings into the variables using parse_str()url_encoded_fmt_stream_map key stores the video’s location information. Later by furthermore decoding of the stream, we will get the raw video link, its quality, format, and itag from it.

getRemoteFilesize() is a custom function which returns the actual video size. So, after all of these this page will show you all the available video formats with its size and quality and a download link as a table format like below image.

List all available video formats with size, quality, and download link as a table format

Extract the Video ID from the Youtube Video Link

function.php

function getVideoId($url) {
    preg_match("#([\/|\?|&]vi?[\/|=]|youtu\.be\/|embed\/)([a-zA-Z0-9_-]+)#", $url, $matches);
    return $matches;
}

getVideoId() function takes the video link as a parameter then extracts the video id from it and returns.

Get the Youtube Video Size

functions.php

function getRemoteFilesize($url, $formatSize = true, $useHead = true)
{
    if (false !== $useHead) {
        stream_context_set_default(array('http' => array('method' => 'HEAD')));
    }
    $head = array_change_key_case(get_headers($url, 1));
    // content-length of download (in bytes), read from Content-Length: field
    $clen = isset($head['content-length']) ? $head['content-length'] : 0;
    $biggest_value = 0;
    if(sizeof($clen) > 1) {
        for($i=0; $i<sizeof($clen); $i++) {
            if($clen[$i] > $biggest_value) $biggest_value = $clen[$i];
        }
        $clen = $biggest_value;
    }

    // cannot retrieve file size, return "-1"
    if (!$clen) {
        return -1;
    }

    if (!$formatSize) {
        return $clen; // return size in bytes
    }

    $size = $clen;
    switch ($clen) {
        case $clen < 1024:
            $size = $clen .' B'; break;
        case $clen < 1048576:
            $size = round($clen / 1024, 2) .' KiB'; break;
        case $clen < 1073741824:
            $size = round($clen / 1048576, 2) . ' MiB'; break;
        case $clen < 1099511627776:
            $size = round($clen / 1073741824, 2) . ' GiB'; break;
    }

    return $size;
}

The above PHP function getRemoteFilesize() returns the video size in bytes. But, if you want you can format it and return the size as KB, MB, and GB.

Download the Videos Using PHP Script

download.php

<?php
if(!empty($_GET['url']) && !empty($_GET['title']) && !empty($_GET['mime']) && !empty($_GET['ext'])) {
  $url   = base64_decode($_GET['url']);
  $title = filter_var($_GET['title']);
  $mime  = filter_var($_GET['mime']);
  $ext   = filter_var($_GET['ext']);
  $size  = filter_var($_GET['size']);

  if ($url) {
    // Generate the server headers
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE)
    {
      header('Content-Type: "' . $mime . '"');
      header('Content-Disposition: attachment; filename="' . $title .".". $ext . '"');
      header('Expires: 0');
      header('Content-Length: '.$size);
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
      header("Content-Transfer-Encoding: binary");
      header('Pragma: public');
    }
    else
    {
      header('Content-Type: "' . $mime . '"');
      header('Content-Disposition: attachment; filename="' . $title .".". $ext . '"');
      header("Content-Transfer-Encoding: binary");
      header('Expires: 0');
      header('Content-Length: '.$size);
      header('Pragma: no-cache');
    }

    readfile($url);
    exit;
  }
}
?>

download.php sets the HTTP headers based on the data it received from the query string. And at last, readfile() function outputs the file.

If you face any problem feel free to inform me in the comment section below. Please like and share this tutorial how to download youtube videos using PHP script with others. Kindly subscribe Mitrajit’s Tech Blog to keep yourself updated with the upcoming tutorials.

About Mitrajit

Leave a Reply

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

Prove you are a human *