athlon1600/youtube-downloader
Pure-PHP YouTube downloader library that fetches direct stream links (audio-only and combined audio+video) without shelling out to youtube-dl or using JS interpreters. Simple API: getDownloadLinks() and pick the best format URL.
Install via Composer:
composer require athlon1600/youtube-downloader "^4.0"
Ensure your project uses PHP 7.4+ (required for type declarations).
Basic Usage:
use YouTube\YouTubeDownloader;
$youtube = new YouTubeDownloader();
$downloadOptions = $youtube->getDownloadLinks("https://www.youtube.com/watch?v=EXAMPLE");
$firstFormat = $downloadOptions->getFirstCombinedFormat();
Key Classes:
YouTubeDownloader: Core class for fetching download links.DownloadOptions: Holds stream formats (audio/video/combined).VideoInfo: Metadata about the video (title, duration, etc.).Download a video and stream it directly:
use YouTube\YouTubeStreamer;
$streamer = new YouTubeStreamer();
$streamer->stream($firstFormat->url); // Outputs raw video stream
Fetching Download Links:
$downloadOptions = $youtube->getDownloadLinks($videoUrl);
$combinedFormats = $downloadOptions->getCombinedFormats(); // Prioritize combined audio+video
Handling Age-Restricted Content:
$youtube->getBrowser()->setCookieFile('./cookies.txt'); // Load logged-in session
$youtube->getBrowser()->consentCookies(); // Bypass EU cookie consent
Streaming via Laravel Routes:
Route::get('/stream/{url}', function ($url) {
$streamer = new YouTubeStreamer();
return $streamer->stream($url);
});
Queue Jobs for Batch Downloads:
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class DownloadVideoJob implements ShouldQueue
{
use Queueable;
public function handle() {
$youtube = new YouTubeDownloader();
$downloadOptions = $youtube->getDownloadLinks($this->videoUrl);
// Save to storage or process further
}
}
Cache Video Metadata:
$videoInfo = $downloadOptions->getVideoInfo();
cache()->put("video:{$videoUrl}", $videoInfo, now()->addHours(1));
Leverage VideoInfo for Analytics:
$duration = $videoInfo->duration; // in seconds
$title = $videoInfo->title;
Custom Proxy Support:
$youtube->getBrowser()->setProxy('http://proxy.example.com:8080');
Error Handling:
try {
$downloadOptions = $youtube->getDownloadLinks($videoUrl);
} catch (\YouTube\Exception\YouTubeException $e) {
Log::error("Download failed: " . $e->getMessage());
// Retry logic or fallback
}
PHP Version Requirement:
Class 'YouTube\YouTubeDownloader' not found if using PHP < 7.4.Age-Restricted Videos:
DownloadOptions for private/age-restricted content.setCookieFile() with logged-in session cookies.Throttling:
getCombinedFormats() to avoid split streams.Signature Decryption Failures:
YouTubeException with "Failed to decrypt signature."Deprecated Methods:
getSplitFormats() or VideoDetails (v4.0+).getCombinedFormats() and VideoInfo instead.Inspect Raw Response:
$browser = $youtube->getBrowser();
$response = $browser->get("https://www.youtube.com/watch?v=EXAMPLE");
dd($response->getBody()); // Debug HTML/JS for parsing issues
Enable Verbose Logging:
$browser->setDebug(true); // Logs HTTP requests/responses
Check for Captchas:
HTTP 429, YouTube may require manual intervention (e.g., solving a Captcha).Custom Format Selection:
$formats = $downloadOptions->getAllFormats();
$selected = array_filter($formats, fn($f) => $f->quality === '720p');
Extend JsonObject for Metadata:
class ExtendedVideoInfo extends \YouTube\JsonObject {
public function getCustomField() {
return $this->customField ?? null;
}
}
Override Browser for Testing:
$youtube->setBrowser(new \YouTube\Browser([
'curl' => [
'CURLOPT_TIMEOUT' => 30,
],
]));
Cookie File Format:
setCookieFile()..youtube.com TRUE / FALSE 1715456000 session_id YOUR_SESSION_ID
User-Agent Spoofing:
$youtube->getBrowser()->setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
Reuse YouTubeDownloader Instance:
$youtube = new YouTubeDownloader(); // Initialize once (e.g., in a service container)
Avoid Redundant Calls:
DownloadOptions if reusing the same URL:
$cacheKey = "yt_download:{$videoUrl}";
if (!$downloadOptions = cache()->get($cacheKey)) {
$downloadOptions = $youtube->getDownloadLinks($videoUrl);
cache()->put($cacheKey, $downloadOptions, now()->addMinutes(5));
}
How can I help you explore Laravel packages today?