Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Youtube Downloader Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install via Composer:

    composer require athlon1600/youtube-downloader "^4.0"
    

    Ensure your project uses PHP 7.4+ (required for type declarations).

  2. Basic Usage:

    use YouTube\YouTubeDownloader;
    
    $youtube = new YouTubeDownloader();
    $downloadOptions = $youtube->getDownloadLinks("https://www.youtube.com/watch?v=EXAMPLE");
    $firstFormat = $downloadOptions->getFirstCombinedFormat();
    
  3. Key Classes:

    • YouTubeDownloader: Core class for fetching download links.
    • DownloadOptions: Holds stream formats (audio/video/combined).
    • VideoInfo: Metadata about the video (title, duration, etc.).

First Use Case

Download a video and stream it directly:

use YouTube\YouTubeStreamer;

$streamer = new YouTubeStreamer();
$streamer->stream($firstFormat->url); // Outputs raw video stream

Implementation Patterns

Core Workflows

  1. Fetching Download Links:

    $downloadOptions = $youtube->getDownloadLinks($videoUrl);
    $combinedFormats = $downloadOptions->getCombinedFormats(); // Prioritize combined audio+video
    
  2. Handling Age-Restricted Content:

    $youtube->getBrowser()->setCookieFile('./cookies.txt'); // Load logged-in session
    $youtube->getBrowser()->consentCookies(); // Bypass EU cookie consent
    
  3. Streaming via Laravel Routes:

    Route::get('/stream/{url}', function ($url) {
        $streamer = new YouTubeStreamer();
        return $streamer->stream($url);
    });
    

Integration Tips

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

Advanced Patterns

  • 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
    }
    

Gotchas and Tips

Pitfalls

  1. PHP Version Requirement:

    • Error: Class 'YouTube\YouTubeDownloader' not found if using PHP < 7.4.
    • Fix: Upgrade to PHP 7.4+ or use v3.x (deprecated).
  2. Age-Restricted Videos:

    • Error: Empty DownloadOptions for private/age-restricted content.
    • Fix: Use setCookieFile() with logged-in session cookies.
  3. Throttling:

    • Error: Slow downloads (<100 KB/s) due to YouTube throttling.
    • Workaround: Use getCombinedFormats() to avoid split streams.
  4. Signature Decryption Failures:

    • Error: YouTubeException with "Failed to decrypt signature."
    • Debug: Check if YouTube updated its obfuscation (see issue #99).
  5. Deprecated Methods:

    • Error: getSplitFormats() or VideoDetails (v4.0+).
    • Fix: Use getCombinedFormats() and VideoInfo instead.

Debugging Tips

  • 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:

    • If you see HTTP 429, YouTube may require manual intervention (e.g., solving a Captcha).

Extension Points

  1. Custom Format Selection:

    $formats = $downloadOptions->getAllFormats();
    $selected = array_filter($formats, fn($f) => $f->quality === '720p');
    
  2. Extend JsonObject for Metadata:

    class ExtendedVideoInfo extends \YouTube\JsonObject {
        public function getCustomField() {
            return $this->customField ?? null;
        }
    }
    
  3. Override Browser for Testing:

    $youtube->setBrowser(new \YouTube\Browser([
        'curl' => [
            'CURLOPT_TIMEOUT' => 30,
        ],
    ]));
    

Config Quirks

  • Cookie File Format:

    • Use Chrome/Firefox cookie export (Netflix format) for setCookieFile().
    • Example:
      .youtube.com   TRUE   /   FALSE   1715456000  session_id  YOUR_SESSION_ID
      
  • User-Agent Spoofing:

    • Some videos block non-browser UAs. Use:
      $youtube->getBrowser()->setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
      

Performance Tips

  • Reuse YouTubeDownloader Instance:

    $youtube = new YouTubeDownloader(); // Initialize once (e.g., in a service container)
    
  • Avoid Redundant Calls:

    • Cache 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));
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity