Introduction:
In today's digital age, video content is king, and YouTube is the reigning monarch. However, sometimes you may want to watch your favorite YouTube videos offline. In this tutorial, we'll show you how to create a PHP-based YouTube video downloader that you can integrate into your website.
Step 1: Obtaining a YouTube Data API Key:
To interact with the YouTube Data API, you'll need an API key. Follow these steps to obtain one:
- Go to the Google Developers Console.
- Create a new project (if you don't have one already).
- Enable the YouTube Data API for your project.
- Create credentials and obtain your API key.
$apiKey = "API_KEY";
$videoUrl = "YOUTUBE_VIDEO_URL";
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $videoUrl, $match);
$youtubeVideoId = $match[1];
$videoMeta = json_decode(getYoutubeVideoMeta($youtubeVideoId, $apiKey));
$videoTitle = $videoMeta->videoDetails->title;
$videoFormats = $videoMeta->streamingData->formats;
foreach ($videoFormats as $videoFormat) {
$url = $videoFormat->url;
if ($videoFormat->mimeType)
$mimeType = explode(";", explode("/", $videoFormat->mimeType)[1])[0];
else
$mimeType = "mp4";
<a
href="video-downloader.php?link=echo urlencode($url) &title=echo urlencode($videoTitle) &type=echo $mimeType; ">
Download Video</a>
function getYoutubeVideoMeta($videoId, $key)
{
$ch = curl_init();
$curlUrl = 'https://www.youtube.com/youtubei/v1/player?key=' . $key;
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$curlOptions = '{"context": {"client": {"hl": "en","clientName": "WEB",
"clientVersion": "2.20210721.00.00","clientFormFactor": "UNKNOWN_FORM_FACTOR","clientScreen": "WATCH",
"mainAppWebInfo": {"graftUrl": "/watch?v=' . $videoId . '",}},"user": {"lockedSafetyMode": false},
"request": {"useSsl": true,"internalExperimentFlags": [],"consistencyTokenJars": []}},
"videoId": "' . $videoId . '", "playbackContext": {"contentPlaybackContext":
{"vis": 0,"splay": false,"autoCaptionsDefaultOn": false,
"autonavState": "STATE_NONE","html5Preference": "HTML5_PREF_WANTS","lactMilliseconds": "-1"}},
"racyCheckOk": false, "contentCheckOk": false}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlOptions);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$curlResult = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
return $curlResult;
}
}
3 Comments
Very nice, its really helpful article thank for sharing sir
ReplyDeletewe are using the above code but presently its not working can you please fix the code and update
ReplyDeletenot working.
ReplyDelete