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 a full-time 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 videos using PHP. This YouTube downloader PHP script 2021 helps you to download 90% of Youtube videos from Youtube.
Main Features of this YouTube Videos downloader
- Easy to Install
- Easy to Customize (This is a very basic PHP script, and easily customizable)
- Fast Loading without cache mechanism
- No Database Required.
- No installation required, just copy-paste the script to your web server that runs PHP
First things first, we have the below scripts to work YouTube downloader.
- index.php
- class.youtube.php
- downloader.php
First, we will examine the class.youtube.php
as this is the core file that executes important features for downloading a video from YouTube.
getYouTubeCode
– Get the YouTube code from a video URLprocessVideo
– 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 it’s ok, then move to the 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 confirm 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 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); }
I hope everyone enjoyed this article, don’t forget to share this article with your peers.
You can download this source code from GitHub Repo
UPDATE(20 Aug 2020)
The adaptive formats in YouTube provide videos with video only and audios with audio-only options. But we have updated the script with two other formats that are 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.mp4
Relates Articles
- Show Thumbnail Image from YouTube Video URL using PHP
- Get YouTube Video Thumbnail URL using PHP
- Get a YouTube video thumbnail from the YouTube API
Don’t work, it download a file that is not a video.
Some videos will not work as it is restricted. I have added a log in the class file, please update your files and check again. Now you can see the status writing to log file. And also please try with this url and update me. https://www.youtube.com/watch?v=OK_JCtrrv-c
Hey, this works pretty well but a simple problem when I want to download the full playlist but the script won’t work, and got some errors. Update script for download playlist.
At the moment, this script will work only for an individual video.
hi pleassssssssssss ansower me i have sever and domin its not working its working onely on localhost!!
What is the config of the server ?
bhai its unbeliveable. working properly
thanks a lot
thanks thanks thanks thanks
Thanks for helpful Tutorial Guys.
If you guys need fully functional and up-to-date Youtube Downloader along with other sources as well you should take a look on https://xlscripts.com/php-scripts/video-downloader-script-all-in-one-video-downloader/
Just my two cents
Cheers
Doesnt work and cant get tech support to answer me.
Very good. It works perfectly.
This script is run with localhost?
Yes
i Got This Error
Notice: Undefined index: url_encoded_fmt_stream_map in D:\xampp\htdocs\simple-down\class.youtube.php on line 45
Notice: Undefined index: type in D:\xampp\htdocs\simple-down\class.youtube.php on line 52
Notice: Undefined index: url in D:\xampp\htdocs\simple-down\class.youtube.php on line 55
Notice: Undefined offset: 1 in D:\xampp\htdocs\simple-down\class.youtube.php on line 56
Notice: Undefined index: quality in D:\xampp\htdocs\simple-down\class.youtube.php on line 57
how to fix it ?
Updated the code with latest YouTube changes. Download from GitHub repo. Let us know if it’s works
Link to new code please
You can download it from the linked github url
Don’t work.
link: https://www.youtube.com/watch?v=X5Tn0IhgMEk
NOTICE:
Undefined index: url_encoded_fmt_stream_map in C:\wamp\www\Simple-YouTube-Downloader-master\class.youtube.php on line 45
Undefined index: type in C:\wamp\www\Simple-YouTube-Downloader-master\class.youtube.php on line 52
Undefined index: url in C:\wamp\www\Simple-YouTube-Downloader-master\class.youtube.php on line 55
Undefined offset: 1 in C:\wamp\www\Simple-YouTube-Downloader-master\class.youtube.php on line 56
Undefined index: quality in C:\wamp\www\Simple-YouTube-Downloader-master\class.youtube.php on line 57
Updated the code with latest YouTube changes. Download from GitHub repo. Let us know if it’s works
It’s still not working
Please share the video url?
it is working for me
Thanks dude, congratulations.
https://www.youtube.com/watch?v=DUBkmULoBhA
Notice: Undefined property: stdClass::$adaptiveFormats in C:\xampp\htdocs\ytd2\class.youtube.php on line 34
Your code only works with some of the yt video. Please fix it
In this simple script, we are using publicly available YouTube API (https://youtube.com/get_video_info?video_id=ID and it’s restricted to show licensed content’s download links. You are not supposed download a licensed material unless you pay for it.
Not sure how those other apis works, I should invest some time to dig in to that..
Is there any other YouTube API through which we can download other youtube videos as well?
Why this code not working on live server?
It’s working in live servers- https://tools.tutsplanet.com/test/
It’s downloading a file in html format and definately that’s not a video
Notice: Undefined property: stdClass::$adaptiveFormats in G:\xampp\htdocs\youtube\class.youtube.php on line 34
Same. The code works but not every video. Try this link which they provided: https://www.youtube.com/watch?v=OK_JCtrrv-c
This link works for me. Don;t know which videos this code accepts for download though.
Do share if you have found something else please.
It will take Huge Bandwidth Because you are using Readfile
First of all congratulations.
What about .mp3 download ?
Thank you
Notice: Undefined property: stdClass::$url in C:\xampp\htdocs\class.youtube.php on line 51
bro i have same problem
Notice: Undefined property: stdClass::$url in E:\xampp\htdocs\youtube\second\class.youtube.php on line 52
could you solved it if yes than please send me the updated file at [email protected]
thank you
https://www.tutsplanet.com/a-simple-youtube-video-downloader-script-in-php/#comment-4607
YouTube Thumbnail Downloader HD If you want to download the thumbnail of any YouTube video, with HD quality and absolutely free.whenever you download YouTube video thumbnails you have different qualities of picture whenever you download a YouTube thumbnail you have many qualities and your wish is that you download in your favorite quality you have been provided in many qualities providing you HD quality quality 720P HD and Full HD and 1080 and many other pixels
sir i have also same problem
Notice: Undefined property: stdClass::$url in E:\xampp\htdocs\youtube\second\class.youtube.php on line 52
no sound
Its working fine and can download the videos in any avaiable quality using this code.
Thanks
Hello.
Could you give some advice or even write what to do so that the script does not pump the video to pk, but saves it to the server?
No sound on videos? please help
Just read the update at the post bottom. And please try with the updated version of code from Git
Hello
Am getting this error on some videos
Notice: Undefined property: stdClass::$url
How to resolve this?
Also github Url?
Hello
Am getting this error on some videos
Notice: Undefined index: url
How to resolve this?
also your github link?
Hey, the script is working thankyou man.!
kuttynews
Hello admin,
Script is working. But the videos don’t have any sound. Can you please help in this matter why videos don’t have sound ?? I would really appreciate if you help in this. You already did a great job by sharing this code.
Thanks
We have updated the post, please read the update section added at the bottom of the post and try to pull the git repo again.
woah this weblog is excellent i like reading your posts.
Keep up the great work! You know, many peersons are searching around for
this information, you could help them greatly.
thank you so much
Nicely written and done my friend!
I’ve only just begun writing myself in the last few days and noticed manjy writers simply
rehash olld content but add ery littloe of worth. It’s
fantastic to read a helpful article of some true valuie to myself and your other followers.
It’s going down onn the lisst of things I need to replicate as a new
blogger. Reader engagement and content quality aree king.
Many terrific thoughts; you have definitely made it on my list
of sites to follow!
Keep up the excellent work!
All the best,
Lem
It’s a shame you don’t have a donate button! I’d definitely donate to this outstanding blog!
I guess for now i’ll settle for bookmarking and adding your RSS feed to
my Google account. I look forward to fresh updates and will talk about this site with my Facebook group.
Talk soon!
Notice: Undefined variable: formats in C:\xampp\htdocs\index.php on line 80
Notice: Undefined property: stdClass::$url in C:\xampp\htdocs\class.youtube.php on line 52
This is not just you, it happens on all my Apache2 servers. Luckily I’m using Nginx, which doesn’t show any errors by default. The script is working fine on both, if you look past the loads of errors on Apache.
change the line 80 like this this will remove undefinied variable
if(isset($formats))
Why is it that various other download sites and youtube-dl have no trouble finding the googlevideo.com URLs for videos with music, but this script doesn’t find anything for almost every video with music? Normal videos seem to work fine, official audio or music videos give an error. I get that there are restricted videos, but what are the other parties mentioned doing different? Thanks for the script anyway, this is just out of curiosity!
I have a problem
Notice: Undefined variable: formats in E:\xampp\htdocs\Simple-YouTube-Downloader-master\index.php on line 80
Why can’t I download from my phone
This page certainly has all of the info I needed about this subject and didn’t know who
to ask.
Hi there,
Thanks for this great script, its working fine on my live server on pc/laptop but on mobile phones when i try to download its shows ” server problem” during downloading and not able to download.
Can I fetch a video size package !
Is there a possibility to bring more information about the video?
hi! thanks for script & tutorial, let me ask how to format as audio?
Hey There. I found your blog the usage of msn. That is a very
well written article. I will make sure to bookmark it and return to learn extra of your helpful info.
Thank you for the post. I’ll definitely return.
What’s up it’s me, I am also visiting this web site daily, this web page is truly nice and the visitors are in fact sharing nice thoughts.
bruh i dont want to fetch all size video on table Videos . i want video only with size 720p and 480p. any idea how to do this? or which line code to change this?
Thanks bro it’s working properly great information keep sharing with us more information.Techbuddies popular tools
Notice: Undefined index: v in C:\xampp\htdocs\api\api1\class.youtube.php on line 20
Check if you have supplied a valid youtube url. Please note that this script is just a demo, so you need tweak the validations and other parts etc?
Warning: failed loading cafile stream: `C:\xampp\apache\bin\curl-ca-bundle.crt’ in C:\dev\class.youtube.php on line 30
Warning: file_get_contents(): Failed to enable crypto in C:\dev\class.youtube.php on line 30
Warning: file_get_contents(https://youtube.com/get_video_info?video_id=bCiSELRb1oQ): failed to open stream: operation failed in C:\dev\class.youtube.php on line 30
Notice: Undefined index: player_response in C:\dev\class.youtube.php on line 33
Notice: Trying to get property ‘streamingData’ of non-object in C:\dev\class.youtube.php on line 34
Notice: Trying to get property ‘formats’ of non-object in C:\dev\class.youtube.php on line 34
Notice: Trying to get property ‘streamingData’ of non-object in C:\dev\class.youtube.php on line 35
Notice: Trying to get property ‘adaptiveFormats’ of non-object in C:\dev\class.youtube.php on line 35
Notice: Trying to get property ‘playabilityStatus’ of non-object in C:\dev\class.youtube.php on line 38
Notice: Trying to get property ‘status’ of non-object in C:\dev\class.youtube.php on line 38
Notice: Undefined index: player_response in C:\dev\class.youtube.php on line 42
This is something because of the .crt file in your localhost installation. Could you please read the below and try to fix that.
https://stackoverflow.com/questions/55526568/failed-loading-cafile-stream-in-file-get-contents
It seems that the video you are trying to download is a licensed one. This is not a replacement for the websites like ytmate and all.
working …… Thanks for share
script works great except that the script gives an error on random videos.
I have a series of videos in a you tube channel, they have all similar information and format.
The first video in the chain won’t download, the rest will.
the error log is a jumble and I can’t really make out what the error is as to why it won’t come up with the file formats when we go to download. I tried this with the default script in the zip file as well, withouth any of my html modifications.
any suggestions?
Could you please share the video urls that you tried to download?
sure… tx!
https://www.youtube.com/watch?v=rIbnVuKRGuY
and now this one too
https://www.youtube.com/watch?v=zr-bmfmwunc
this one below works fine along with the rest of ours. Just the two above won’t work.
https://www.youtube.com/watch?v=9n8IofTINCE
appreciate your insight!
We have spent sometime on this, and realized that Youtube is using cipher signature for some of the videos.
[code][signatureCipher] => s=IAM0ig1ZbIk_OBiVeFrdHJA5pPPBTpWCT68jTmDE2AFIC4DMWj8tsBKUpCvrgkae0x2OaiCrVgTYMqHgRRhUEJCXg[/code]
Please use the below link to understand more about this from the below SO link. At the moment, we have handful stuff, but we will do research on this when we get time.
https://stackoverflow.com/questions/21510857/best-approach-to-decode-youtube-cipher-signature-using-php-or-js
okay, thanks. would like to know if/when you get a work around for this.
Well, it works well in some videos but in others it doesn’t … example: https://www.youtube.com/watch?v=GO9cAsNu3nw, it doesn’t work you know why?
hello, thanks for the script it works perfecctly but i will like to customized my url like http;//mydomain.com/youtube/videoid or any other way round.
so i can send for someone to download a particular video without having to enter the video url again
This is just basic setup, you can enhance your own.
YouTube sort link not working.
not work – Notice: Undefined index: v in C:\xampp\htdocs\Simple-YouTube-Downloader-master\class.youtube.php on line 20
help
Bro it’s unbeliveable. working properly
thanks a lot.
Thanks a million!
Its working, doesnt work in localhost but working in my hosting. thanks
I like the script and it works just as simple as it is.
Is there a way to get a shorter download link?
So the link can be shared after creating the download link.
Thank You!
Funktioniert leider bei mir nicht weder local noch gehostet!
Its not working on my localhost..
Please who has got solution? It is not working
Warning: file_get_contents(https://youtube.com/get_video_info?video_id=OK_JCtrrv-c): failed to open stream: HTTP request failed! HTTP/1.0 410 Gone in C:\xampp\htdocs\youtube\class.youtube.php on line 30
Notice: Undefined index: player_response in C:\xampp\htdocs\youtube\class.youtube.php on line 33
Notice: Trying to get property ‘streamingData’ of non-object in C:\xampp\htdocs\youtube\class.youtube.php on line 34
Notice: Trying to get property ‘formats’ of non-object in C:\xampp\htdocs\youtube\class.youtube.php on line 34
Notice: Trying to get property ‘streamingData’ of non-object in C:\xampp\htdocs\youtube\class.youtube.php on line 35
Notice: Trying to get property ‘adaptiveFormats’ of non-object in C:\xampp\htdocs\youtube\class.youtube.php on line 35
Notice: Trying to get property ‘playabilityStatus’ of non-object in C:\xampp\htdocs\youtube\class.youtube.php on line 38
Notice: Trying to get property ‘status’ of non-object in C:\xampp\htdocs\youtube\class.youtube.php on line 38
Notice: Undefined index: player_response in C:\xampp\htdocs\youtube\class.youtube.php on line 42