Script php videos youtube

Закачка видео с youtube с помощью php

Будучи счастливым отцом семейства, передо мной довольно долго стояла задача поиска интересных мультиков для своих чад на просторах ютуба, с последующей скачкой роликов для показа детям на телевизоре.

Задача сама по себе не сложная. Основной труд составляет процесс сохранения роликов: нужно скопипастить ссылку, найти соответствующий сервис, воспользоваться им, скачать выданный ролик. Все это довольно нудно и скучно. Поэтому было решено сделать инструмент который будет закачивать ролики, примерно как wget по списку url из файла.

Я довольно давно знал о существовании программы youtube-dl. Программа умеет скачивать ролики с гигантского количества сайтов, в том числе и с ютуба и делает она это хорошо. Изначально инструмент работает из под *nix, но, к счастью, есть версия и для windows.

Один большой минус: не умеет работать со списком url.

Будучи немного знаком с языком программирования php решил научить yutube-dl работать со списком url при помощи php-cli.

1. Скачана последняя версия php (7.0.32)

2. В переменные окружения добавлен путь к php.exe для того что бы запускать скрипты просто из командной строки. Например

Читайте также:  Python узнать дату создания папки

3. Написан вот такой скрипт:

 $url)< echo $colors->getColoredString('Загрузка ' . $url, "green", null); $command = 'youtube-dl ' . implode(' ', $options) . ' ' . $url; exec($command); > echo $colors->getColoredString(PHP_EOL."Очистка списка".PHP_EOL, "red", null); fopen("/path/to/list.txt", "w"); echo $colors->getColoredString("Готово", "green", null); ?> 

youtube-dl.exe кладем рядом со скриптом.
list.txt — список url вида youtube.com/watch?v=xxxxxx, каждый url с новой строки.
colors.class.php — класс для раскраски сообщений скрипта (он не обязателен).

youtube-dl запускается с параметром -f best, что означает поиск и скачку лучшего по качеству видео и аудио ролика.

Вот и все. Теперь можно в процессе просмотра мультиков складывать нужные url в файл, а потом один раз запустить php скрипт. Он все скачает за один заход и сохранит в нужную папку.

Спасибо за внимание. Надеюсь, кому нибудь данная информация будет полезна.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP script for downloading videos from youtube; also parsing youtube feed into RSS enclosures for podcatchers

License

jeckman/YouTube-Downloader

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

THIS PROJECT IS NO LONGER ACTIVELY DEVELOPED

PHP Library with Web UI to download videos from YouTube.

  • Create a library that delivers data and download links for youtube videos.
  • Create a UI for downloading the videos.
  • Have no external dependencies to other services.
  • Have no external dependencies to other libraries in production.
  • Installation should be simple (unzip on server and go)

To achieve this goals this project contains two parts:

  1. A semantic versioning 2 following PHP library that delivers data and download links for youtube videos.
  2. A Web interface that uses this library

Support for Cipher signature

YouTube Downloader supports YouTube videos with a cipher signature too. 🎉 Please note that this functionality is hidden behind a config flag because it downloads JavaScript code from a 3rd party (YouTube) server and interprets it. This MAY harm your server, if the 3rd party server delivers malicious code.

You can activate this by setting the enable_youtube_decipher_signature to true in /config/custom.php . If the file don’t exists you can simple create it or copy from /config/default.php .

 // in config/custom.php return [ 'enable_youtube_decipher_signature' => true, ];

You must fit at least this requirements to use YouTube-Downloader:

There are multiple ways to set up YouTube-Downloader

  1. Download the code for the newest release: https://github.com/jeckman/YouTube-Downloader/releases
  2. Unzip the code to your web server
  3. Open the folder with your browser
 git clone https://github.com/jeckman/YouTube-Downloader.git 
 git checkout $(git describe --abbrev=0 --tags) 

You can use the PHP library in your project by installing the code via Composer.

The library isn’t available on packagist.org at the moment, so you must add the repository in your composer.json manually. Your composer.json should look like this

Now install the dependencies with $ composer update

Note: Instead of using the master branch you should use a specific release like «jeckman/YouTube-Downloader»: «0.XX» . You can found all releases here.

You can manually visit a web form (the index.php file), enter a YouTube video id, and get in return a list of links showing the various formats in which that video can be downloaded. You can simply choose «save link as» or the equivalent to download the file.

Second, you can directly target the getvideo.php script, passing in a videoID and preferred format, and you will get redirected to the file itself.

  • best = just give me the largest file / best quality
  • free = give the largest version including WebM, lower priority to FLV
  • ipad = ignore WebM and FLV, look for best MP4 file

You can also pass in a specific format number, if you know it.

Note this approach, because it redirects you to the file itself, currently bypasses the proxy option, so if your browser/server setup requires the proxy to work these will fail.

You can subscribe both to YouTube channels and users via RSS. Feeds can be generated in the formats listed above.

Generating a feed for a YouTube channel works as follows:

To generate a feed for a YouTube user:

The generated feed is a standard RSS feed and can be subscribed to in any feed reader.

  1. Backup your config file from config/custom.php .
  2. Delete all files in the project folder
  3. Download the newest release from https://github.com/jeckman/YouTube-Downloader/releases
  4. Unzip the code to your project folder
  5. Place your config file back to config/custom.php .

Fetch the master branch and checkout the latest annotated tag.

git remote update git fetch origin master git checkout $(git describe --abbrev=0 --tags master)

Update your composer.json to use the latest version. Then run:

You can help making this project better by reporting bugs or submitting pull requests. Please see our contributing guideline for more information.

About

PHP script for downloading videos from youtube; also parsing youtube feed into RSS enclosures for podcatchers

Источник

PHP YouTube Video Downloader Script

YouTube is almost the numero one platform for hosting videos. It allows users to publish and share videos on a social network.

Downloading YouTube videos is sometimes required. You must read through the YouTube terms and conditions before downloading videos and act according to the permissions given. For example, you may wish to download to have a backup of older videos that will be replaced or removed.

This quick example provides a YouTube Video downloader script in PHP. It has a video URL defined in a PHP variable. It also establishes a key to access the YouTube video meta via API.

Configure the key and store the video URL to get the video downloader link using this script.

Quick example

)%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"; ?> &title=&type="> Download Video 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 = '>,"user": , "request": >, "videoId": "' . $videoId . '", "playbackContext": >, "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; > ?> 

This example code works in the following flow to output the link to download the YouTube video.

  1. Get the unique id of the YouTube video from the input URL.
  2. Request YouTube API via PHP cURL post to access the video metadata.
  3. Get the video title, data array in various formats, and MIME type by parsing the cURL response.
  4. Pass the video links, title, and mime types to the video downloader script.
  5. Apply PHP readfile() to download the video file by setting the PHP headerContent-type.

youtube video downloader links php

The below video downloader script is called by clicking the “Download video” link in the browser.

It receives the video title and extension to define the output video file name. It also gets the video link from which it reads the video to be downloaded to the browser.

This script sets the content header in PHP to output the YouTube video file.

Collect YouTube video URL via form and process video downloader script

The quick example has a sample to hardcode the YouTube video URL to a PHP variable.

But, the below code will allow users to enter the video URL instead of the hardcode.

An HTML form will post the entered video URL to process the PHP cURL request to the YouTube API.

After posting the video URL, the PHP flow is the same as the quick example. But, the difference is, that it displays more links to download videos in all the adaptive formats.

 

PHP YouTube Video Downloader Script

URL: ">

if (isset($_POST['submit'])) < preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ])%i', $videoUrl, $match); $youtubeVideoId = $match[1]; require './youtube-video-meta.php'; $videoMeta = json_decode(getYoutubeVideoMeta($youtubeVideoId, $key)); $videoThumbnails = $videoMeta->videoDetails->thumbnail->thumbnails; $thumbnail = end($videoThumbnails)->url; ?>

videoDetails->title; ?> Video title: videoDetails->shortDescription; ?>

streamingData->formats; if (! empty($videoFormats)) < if (@$videoFormats[0]->url == "") < ?>

This YouTube video cannot be downloaded by the downloader!signatureCipher; parse_str(parse_url($signature, PHP_URL_QUERY), $parse_signature); $url = $parse_signature['url'] . "&sig=" . $parse_signature['s']; ?>

?>

With Video & Sound

url == "") < $signature = "https://example.com?" . $videoFormat->signatureCipher; parse_str(parse_url($signature, PHP_URL_QUERY), $parse_signature); $url = $parse_signature['url'] . "&sig=" . $parse_signature['s']; > else < $url = $videoFormat->url; > ?> ?>
Video URL Type Quality Download Video
">View Video mimeType) echo explode(";",explode("/",$videoFormat->mimeType)[1])[0]; else echo "Unknown";?> qualityLabel) echo $videoFormat->qualityLabel; else echo "Unknown"; ?> &title=&type=mimeType) echo explode(";",explode("/",$videoFormat->mimeType)[1])[0]; else echo "mp4";?>"> Download Video
streamingData->adaptiveFormats; include 'adaptive-formats.php'; ?> > ?>

This program will output the following once it has the video downloader response.

php youtube video downloader

PHP cURL script to get the video metadata

The quick example already shows the PHP cURL script used to access the YouTube endpoint to read the file meta.

The above code snippet has a PHP require_once statement for having the cURL post handler.

The youtube-video-meta.php file has this handler to read the video file meta. It receives the unique id of the video and the key used in the PHP cURL parsing.

In a recently posted article, we have collected file meta to upload to Google Drive.

Display YouTube video downloaders in adaptive formats

The landing page shows another table of downloads to get the video file in the available adaptive formats.

The PHP script accesses the adaptiveFormats property of the Youtube video meta-object to display these downloads.

YouTube Videos Adaptive Formats

url; > catch (Exception $e) < $signature = $videoFormat->signatureCipher; parse_str(parse_url($signature, PHP_URL_QUERY), $parse_signature); $url = $parse_signature['url']; > ?> ?>
Type Quality Download Video
mimeType) echo explode(";",explode("/",$videoFormat->mimeType)[1])[0]; else echo "Unknown";?> qualityLabel) echo $videoFormat->qualityLabel; else echo "Unknown"; ?> &title=&type=mimeType) echo explode(";",explode("/",$videoFormat->mimeType)[1])[0]; else echo "mp4";?>">Download Video

Leave a Reply Cancel reply

Источник

Оцените статью