Grabbing youtube video URL from curl or get_video_info

Asked
Active3 hr before
Viewed126 times

6 Answers

grabbingyoutubevideo
90%

So, I am working on a php project and one part of it is grabbing a youtube video url and inserting it into an html5 video tag. I was using a curl call to http://youtube.com/get_video_info?video_id=XXX and getting the right video file urls on my local machine. ,But, when I uploaded my code to my web server and tried to run it, none of the video URLs have worked. The urls seemed fine but some parameters, like IP, where different. I can't understand why it works from my local machine running xampp or mamp but not on my web server. I even tried just doing a curl on the youtube video page and noticed that locally, it would output the page and play the video but on my webserver, all the video calls got 404s.,The link that you extract only works for the IP address from which you extracted it. So, if you extract it from your local machine, it will work in the browser on your machine. However, if you extract it from your server, only the server will be able to access the video file from that link.,I've made a script in PHP to stream youtube videos to clinets recently and I think by alter a little bit of my script can fit your purpose.

Here is my PHP script:

< ? php
@set_time_limit(0); //disable time limit to make sure the whole video is streamed to the client
$id = $_GET['id']; //the youtube video ID
$type = $_GET['type']; //the MIME type of the desired format

parse_str(file_get_contents('http://www.youtube.com/get_video_info?video_id='.$id), $info); //get video info
$streams = explode(',', $info['url_encoded_fmt_stream_map']); //split the stream map into streams

foreach($streams as $stream) {
      parse_str($stream, $real_stream); //parse the splitted stream
      $stype = $real_stream['type']; //the MIME type of the stream
      if (strpos($real_stream['type'], ';') !== false) { //if a semicolon exists, that means the MIME type has a codec in it
         $tmp = explode(';', $real_stream['type']); //get rid of the codec
         $stype = $tmp[0];
         unset($tmp);
      }
      if ($stype == $type && ($real_stream['quality'] == 'large' || $real_stream['quality'] == 'medium' || $real_stream['quality'] == 'small')) { //check whether the format is the desired format 
         header('Content-type: '.$stype); //send the HTTP headers
         header('Transfer-encoding: chunked'); //necessary for streaming
         @readfile($real_stream['url'].
            '&signature='.$real_stream['sig']); //send the content to the client
         ob_flush(); //disable PHP caching
         flush(); //flush the content out
         break;
      }
   } ?
   >
load more v
88%

So, I am working on a php project and one part of it is grabbing a youtube video url and inserting it into an html5 video tag. I was using a curl call to http://youtube.com/get_video_info?video_id=XXX and getting the right video file urls on my local machine. ,Any info about this? Anyway I can grab a youtube video url so that I can play youtube videos in a html5 video tag? Is this why keepvid and sites like that use the damn java applet? ,I've made a script in PHP to stream youtube videos to clinets recently and I think by alter a little bit of my script can fit your purpose.,You should take a look to youtube-dl project I'm pretty sure you can takes some idea to understand the proper way to achieve your goal.

Here is my PHP script:

< ? php
@set_time_limit(0); //disable time limit to make sure the whole video is streamed to the client
$id = $_GET['id']; //the youtube video ID
$type = $_GET['type']; //the MIME type of the desired format

parse_str(file_get_contents('http://www.youtube.com/get_video_info?video_id='.$id), $info); //get video info
$streams = explode(',', $info['url_encoded_fmt_stream_map']); //split the stream map into streams

foreach($streams as $stream) {
      parse_str($stream, $real_stream); //parse the splitted stream
      $stype = $real_stream['type']; //the MIME type of the stream
      if (strpos($real_stream['type'], ';') !== false) { //if a semicolon exists, that means the MIME type has a codec in it
         $tmp = explode(';', $real_stream['type']); //get rid of the codec
         $stype = $tmp[0];
         unset($tmp);
      }
      if ($stype == $type && ($real_stream['quality'] == 'large' || $real_stream['quality'] == 'medium' || $real_stream['quality'] == 'small')) { //check whether the format is the desired format 
         header('Content-type: '.$stype); //send the HTTP headers
         header('Transfer-encoding: chunked'); //necessary for streaming
         @readfile($real_stream['url'].
            '&signature='.$real_stream['sig']); //send the content to the client
         ob_flush(); //disable PHP caching
         flush(); //flush the content out
         break;
      }
   } ?
   >
load more v
72%

Purpose: The article shows the title, description, and thumbnail for a particular YouTube URL link. HTML form requests a YouTube video URL for the given input. ,The titles help the search engine to crawl for the relevant data. ,The following image shows the screen before the user clicks the “Submit URL” button:,Title and Description plays a key role in making the video important and for search engine ranking factors.

65%

getYouTubeCode – Get the YouTube code from a video URL,First, we will examine the class.youtube.php as this is the core file that executes important features for downloading a video from YouTube.,Get a YouTube video thumbnail from the YouTube API,Updated the code with latest YouTube changes. Download from GitHub repo. Let us know if it’s works

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";
   }
} ?
>

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;?>

You may have noticed there is a 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 the 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);

}

A sample command would be

ffmpeg - i videoplayback.mp4 - i videoplayback.m4a - c: v copy - c: a copy output.mp4
load more v
75%

setUrl() – Set the video file URL.,getVideoInfo() – Get the video information using file_get_contents() method in PHP.,Load and initialize Downloader class (YouTubeDownloader).,getVideoDownloadLink() – Get the video download URL with video info (itag, quality, title, mime, and format).

  • Load and initialize Downloader class (YouTubeDownloader).
  • Get the downloader object using getDownloader() function.
  • Set the YouTube URL using setUrl() function.
  • Validate the YouTube video URL using hasVideo() function.
  • Get the video download link and video info using getVideoDownloadLink() function.
  • Force the browser to download the video file from YouTube using PHP.
< ? php // Load and initialize downloader class include_once 'YouTubeDownloader.class.php'; $handler = new YouTubeDownloader();  // Youtube video url $youtubeURL = 'https://www.youtube.com/watch?v=f7wcKoEbUSA';  // Check whether the url is valid if(!empty($youtubeURL) && !filter_var($youtubeURL, FILTER_VALIDATE_URL) === false){     // Get the downloader object     $downloader = $handler->getDownloader($youtubeURL);          // Set the url     $downloader->setUrl($youtubeURL);          // Validate the youtube video url     if($downloader->hasVideo()){         // Get the video download link info         $videoDownloadLink = $downloader->getVideoDownloadLink();                  $videoTitle = $videoDownloadLink[0]['title'];         $videoQuality = $videoDownloadLink[0]['qualityLabel'];         $videoFormat = $videoDownloadLink[0]['format'];         $videoFileName = strtolower(str_replace(' ', '_', $videoTitle)).'.'.$videoFormat;         $downloadURL = $videoDownloadLink[0]['url'];         $fileName = preg_replace('/[^A-Za-z0-9.\_\-]/', '', basename($videoFileName));                  if(!empty($downloadURL)){             // Define header for force download             header("Cache-Control: public");             header("Content-Description: File Transfer");             header("Content-Disposition: attachment; filename=$fileName");             header("Content-Type: application/zip");             header("Content-Transfer-Encoding: binary");                          // Read the file             readfile($downloadURL);         }     }else{         echo "The video is not found, please check YouTube URL.";     } }else{     echo "Please provide valid YouTube URL."; }  ?>
40%

We need the v parameter value from the above Youtube Watch URL (Example: v=NeSuirvA6UE ),to see the response from youtube. We need to parse the token string from the above response.  ,urlparse(youtube_watchurl).query returns the query part of the above URL i.e., “v=NeSuirvA6UE&playnext_from=TL&videos=MS3Hq4oBj08”. We need the value of ‘v’ parameter from this query string. parse_qs() function returns parameter name and value in dictionary format. parse_qs(…)[‘v’][0] returns the value of ‘v’ parameter.,youtube_watchurl is a self explanatory, we store the Youtube Watch URL here –

youtube_watchurl is a self explanatory, we store the Youtube Watch URL here –

youtube_watchurl = "http://www.youtube.com/watch?v=NeSuirvA6UE&playnext_from=TL&videos=MS3Hq4oBj08"

urlparse(youtube_watchurl).query returns the query part of the above URL i.e., “v=NeSuirvA6UE&playnext_from=TL&videos=MS3Hq4oBj08”. We need the value of ‘v’ parameter from this query string. parse_qs() function returns parameter name and value in dictionary format. parse_qs(…)[‘v’][0] returns the value of ‘v’ parameter.

video_id = parse_qs(urlparse(youtube_watchurl).query)['v'][0];

Just try

curl "http://www.youtube.com/get_video_info?&video_id=NeSuirvA6UE"

to see the response from youtube. We need to parse the token string from the above response.
 

urlopen('http://www.youtube.com/get_video_info?&video_id=' + video_id).read().decode('utf-8')
parse_qs(unquote(urlopen('http://www.youtube.com/get_video_info?&video_id=' + video_id).read().decode('utf-8')))['token'][0])

example token value:

vjVQa1PpcFNWkxk6GpwXYrIxVZ - 1 iDcF_E9emDZ4UKA % 3 D

Now we have video id and token string, let’s put these value into the direct url to download the video. The format of the Direct URL:

http: //www.youtube.com/get_video?video_id=video_id&t=token&fmt=18

Example Direct URL:

http: //www.youtube.com/get_video?video_id=NeSuirvA6UE&t=vjVQa1PpcFNWkxk6GpwXYrIxVZ-1iDcF_E9emDZ4UKA%3D&fmt=18

The above URL redirected me to below URL

http: //v12.lscache4.c.youtube.com/videoplayback?ip=0.0.0.0&sparams=id,expire,ip,ipbits,itag,algorithm,burst,factor,oc:U0dWSFZUVl9FSkNNNl9OTlpB&fexp=903801,903206&algorithm=throttle-factor&itag=18&ipbits=0&burst=40&sver=3&expire=1273698000&key=yt1&signature=5F8E3C3EABC00FE77AB5699811B13957CA95CFFD.14D37482C6E22D91D08770C6630EE3BE3BF9732D&factor=1.25&id=35e4ae8abbc0e941

And that’s it we use the above direct link to download and write it to a file

open(video_id + '.mp4', 'wb').write(urlopen("http://www.youtube.com/get_video?video_id=%s&t=%s&fmt=18" % (video_id, parse_qs(unquote(urlopen('http://www.youtube.com/get_video_info?&video_id=' + video_id).read().decode('utf-8')))['token'][0])).read())
load more v

Other "grabbing-youtube" queries related to "Grabbing youtube video URL from curl or get_video_info"