>_ DevTrendsen

Language

Home

Languages

Sections

Frontend Backend Mobile DevOps AI / ML GameDev Blockchain Embedded Security
PHP

How to Download YouTube Videos with Pure PHP Without the Headache

A familiar story: you need to add video downloading to your project or just grab a direct stream URL. The first thing that comes to mind is the good old youtube-dl. But problems start right away. You have to deal with system calls, manage Python installations in your container, and hope the binary doesn't break at the worst possible time.

Recently I came across the youtube- down-loader repository by developer Athlon1600. It's an attempt to build a proper library in pure PHP that doesn't drag along a bunch of external dependencies and external tools.

What's the point of this project

The author puts it plainly: most PHP libraries for YouTube are either abandoned from five years ago or just wrap calls to Python scripts. This project follows a different idea. There are no JavaScript interpreters or shell calls. Just PHP and standard HTTP requests.

The project is inspired by giants like yt-dlp, but adapted for the specifics of web servers. If you need to quickly integrate downloading functionality into an existing PHP application, this is probably the easiest path.

What the library can do

The tool covers the basic needs that developers face when working with video hosting sites.

Getting direct links

The most common scenario is feeding a video URL and getting a list of available formats. The library returns a DownloadOptions object containing links to videos of different quality, audio tracks, and combined streams.

use YouTube\YouTubeDownloader;
use YouTube\Exception\YouTubeException;

$youtube = new YouTubeDownloader();

try {
    $downloadOptions = $youtube->getDownloadLinks("https://www.youtube.com/watch?v=aqz-KE-bpKQ");

    if ($downloadOptions->getAllFormats()) {
        // Берем первый попавшийся формат, где есть и звук, и видео
        echo $downloadOptions->getFirstCombinedFormat()->url;
    }
} catch (YouTubeException $e) {
    echo 'Ошибка: ' . $e->getMessage();
}

Streaming video through the server

Sometimes you can't expose the direct link to the user (for example, to avoid exposing your server IP or bypass restrictions). The library has a built-in YouTubeStreamer that lets you proxy the stream through your backend.

$youtube = new \YouTube\YouTubeStreamer();
// Передаем URL потока, полученный ранее
$youtube->stream('https://r4---sn-n4v7knll.googlevideo.com/videoplayback?...');

Working with restrictions and cookies

YouTube doesn't like automation. If a video has age restrictions or is only available to authorized users, a regular request will return an error. The library lets you supply a cookies file exported from your browser. It's a "hacky" but working way to make the service think the request is coming from a real person.

$youtube = new YouTubeDownloader();
$youtube->getBrowser()->setCookieFile('./cookies.txt');
$youtube->getBrowser()->setUserAgent('Mozilla/5.0...');

By the way, there's even a consentCookies() method that programmatically clicks the "Accept" button in European cookie notices. A small thing, but it saves time on debugging.

How it works under the hood

Instead of parsing the page with regex (which is unreliable), the library tries to mimic client behavior. It parses YouTube's internal data structures, finds signatures, and decodes links. If you're curious about how the YouTube protocol reverse engineering actually works, the author left a great collection of links to articles and source code of other parsers in the README.

Practical use cases

Where this can really come in handy:

  1. Telegram bots. If you're writing a video downloading bot, a PHP library lets you avoid spawning microservices in Python.
  2. Preview services. When you need to quickly pull metadata or a screenshot of a video without using the heavy and rate-limited YouTube API.
  3. Content archiving. Creating local copies of important videos for internal company needs.

Is it worth using

The project looks active: tests pass, commits come in regularly (which is critical for tools like this since YouTube constantly changes its markup).

On the downside — there's currently an issue with download speed. YouTube often throttles requests to 100 kbps if they seem suspicious. The author knows about this and has it on the todo list. Also, there's no built-in video and audio merging via ffmpeg yet, so if you need 4K (where audio and video always come separately), you'll have to write this logic yourself.

If you need a simple and straightforward PHP solution without extra overhead, youtube- down-loader is a great candidate for your composer.json.

Related projects