Extracting YouTube Videos Using PHP

I’d like to share this nice PHP snippet that some of you would find useful. It’s a code that extracts the video title and the download URL from a YouTube page and then initiates a download sequence.

There are already a lot of methods posted out there on the web on how to do this (and not just by using PHP) but this one is rather new. I found it at Snipplr and it’s posted by codespartan.

The code is as follows:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$url = (isset($_POST['url']) && !empty($_POST['url'])) ? $_POST['url'] : false;
if (!$url) {
echo "Please enter a URL.";
} else {
$source = file_get_contents($url);
$source = urldecode($source);
// Extract video title.
$vTitle_results_1 = explode('<title>', $source);
$vTitle_results_2 = explode('</title>', $vTitle_results_1[1]);
$title = trim(str_replace(' - YouTube', '', trim($vTitle_results_2[0])));
// Extract video download URL.
$dURL_results_1 = explode('url_encoded_fmt_stream_map": "url=', $source);
$dURL_results_2 = explode('\u0026quality', $dURL_results_1[1]);
// Force download of video.
$file = str_replace(' ', '_', strtolower($title)).'.webm';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: video/webm");
header("Content-Transfer-Encoding: binary");
readfile($dURL_results_2[0]);
exit;
}
}
?>
<form method="post">
 <label for="url">URL:</label> 
 <input type="text" name="url" value="" id="url"> 
 <input type="submit" name="submit" value="Download">
</form>

Feel free to send feedback to the code’s submitter at the Snipplr page.

Incoming search terms for the article:

Related Posts

Turn A Photo Into A Vector Portrait With Photoshop

Correctly Embed Watermarks In Portrait And Landscape Photos Using Conditional Actions In Photoshop CS6.1

Oregon-Inspired Photoshop Tutorial

Create Google Play’s Tab Navigation Using jQuery And CSS

1 Comment

  1. Name

    06.20.2012

    This code dos`nt work