Saturday, April 20, 2024
HomePHPPHP YouTube Video Downloader Script

PHP YouTube Video Downloader Script


by Vincy. Final modified on September fifteenth, 2022.

YouTube is nearly the numero uno platform for internet hosting movies. It permits customers to publish and share movies, extra like a social community.

Downloading YouTube movies is typically required. You will need to learn by the YouTube phrases and circumstances earlier than downloading movies and act in accordance with the permissions given. For instance you might want to obtain to have a backup of older movies which are going to get replaced or eliminated.

This fast instance gives a YouTube Video downloader script in PHP. It has a video URL outlined in a PHP variable. It additionally establishes a key to entry the YouTube video meta by way of API.

Configure the important thing and retailer the video URL to get the video downloader hyperlink utilizing this script.

Fast instance

<?php
$apiKey = "API_KEY";
$videoUrl = "YOUTUBE_VIDEO_URL";
preg_match('%(?:youtube(?:-nocookie)?.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/ ]{11})%i', $videoUrl, $match);
$youtubeVideoId = $match[1];
$videoMeta = json_decode(getYoutubeVideoMeta($youtubeVideoId, $apiKey));
$videoTitle = $videoMeta->videoDetails->title;
$videoFormats = $videoMeta->streamingData->codecs;
foreach ($videoFormats as $videoFormat) {
    $url = $videoFormat->url;
    if ($videoFormat->mimeType)
        $mimeType = explode(";", explode("https://phppot.com/", $videoFormat->mimeType)[1])[0];
    else
        $mimeType = "mp4";
    ?>
<a
    href="https://phppot.com/php/php-youtube-video-downloader/video-downloader.php?hyperlink=<?php echo urlencode($url)?>&title=<?php echo urlencode($videoTitle)?>&sort=<?php echo $mimeType; ?>">
    Obtain Video</a>
<?php
}

operate getYoutubeVideoMeta($videoId, $key)
{
    $ch = curl_init();
    $curlUrl="https://www.youtube.com/youtubei/v1/participant?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="{"context": {"consumer": {"hl": "en","clientName": "WEB",
        "clientVersion": "2.20210721.00.00","clientFormFactor": "UNKNOWN_FORM_FACTOR","clientScreen": "WATCH",
        "mainAppWebInfo": {"graftUrl": "/watch?v=" . $videoId . '",}},"person": {"lockedSafetyMode": false},
        "request": {"useSsl": true,"internalExperimentFlags": [],"consistencyTokenJars": []}},
        "videoId": "' . $videoId . '",  "playbackContext": {"contentPlaybackContext":
        {"vis": 0,"splay": false,"autoCaptionsDefaultOn": false,
        "autonavState": "STATE_NONE","html5Preference": "HTML5_PREF_WANTS","lactMilliseconds": "-1"}},
        "racyCheckOk": false,  "contentCheckOk": false}';
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlOptions);
    $headers = array();
    $headers[] = 'Content material-Sort: software/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 instance code works within the following stream to output the hyperlink to obtain the YouTube video.

  1. Get the distinctive id of the YouTube video from the enter URL.
  2. Request YouTube API by way of PHP cURL put up to entry the video metadata.
  3. Get video title, knowledge array in varied codecs, and MIME sort by parsing the cURL response.
  4. Cross the video hyperlinks, title and mime varieties to the video downloader script.
  5. Apply PHP readfile() to obtain the video file by setting the PHP header Content material-type.

youtube video downloader links php

The under video downloader script known as by clicking the “Obtain video” hyperlink within the browser.

It receives the video title, and extension to outline the output video file title. It additionally will get the video hyperlink from which it reads the video to be downloaded to the browser.

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

video-downloader.php

<?php
// this PHP script reads and downloads the video from YouTube
$downloadURL = urldecode($_GET['link']);
$downloadFileName = urldecode($_GET['title']) . '.' . urldecode($_GET['type']);
if (! empty($downloadURL) && substr($downloadURL, 0, 8) === 'https://') {
    header("Cache-Management: public");
    header("Content material-Description: File Switch");
    header("Content material-Disposition: attachment;filename="$downloadFileName"");
    header("Content material-Switch-Encoding: binary");
    readfile($downloadURL);
}
?>

View Demo

Acquire YouTube video URL by way of type and course of video downloader script

Within the fast instance, it has a pattern to hardcode the YouTube video URL to a PHP variable.

However, the under code will permit customers to enter the video URL as an alternative of the hardcode.

An HTML type will put up the entered video URL to course of the PHP cURL request to the YouTube API.

After posting the video URL, the PHP stream is similar as the fast instance. However, the distinction is, that it shows extra hyperlinks to obtain movies in all of the adaptive codecs.

index.php

<type methodology="put up" motion="">
    <h1>PHP YouTube Video Downloader Script</h1>
    <div class="row">
        <enter sort="textual content" class="inline-block" title="youtube-video-url">
        <button sort="submit" title="submit" id="submit">Obtain Video</button>
    </div>
</type>
<?php
if (isset($_POST['youtube-video-url'])) {
    $videoUrl = $_POST['youtube-video-url'];
    ?>
<p>
    URL: <a href="https://phppot.com/php/php-youtube-video-downloader/<?php echo $videoUrl;?>"><?php echo $videoUrl;?></a>
</p>
<?php
}
if (isset($_POST['submit'])) {
    preg_match('%(?:youtube(?:-nocookie)?.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/ ]{11})%i', $videoUrl, $match);
    $youtubeVideoId = $match[1];
    require './youtube-video-meta.php';
    $videoMeta = json_decode(getYoutubeVideoMeta($youtubeVideoId, $key));
    $videoThumbnails = $videoMeta->videoDetails->thumbnail->thumbnails;
    $thumbnail = finish($videoThumbnails)->url;
    ?>
<p>
    <img src="<?php echo $thumbnail; ?>">
</p>
<?php $videoTitle = $videoMeta->videoDetails->title; ?>
<h2>Video title: <?php echo $videoTitle; ?></h2>
<?php
    $shortDescription = $videoMeta->videoDetails->shortDescription;
    ?>
<p><?php echo str_split($shortDescription, 100)[0];?></p>
<?php
    $videoFormats = $videoMeta->streamingData->codecs;
    if (! empty($videoFormats)) {
        if (@$videoFormats[0]->url == "") {
            ?>
<p>
    <robust>This YouTube video can't be downloaded by the downloader!</robust><?php
            $signature = "https://instance.com?" . $videoFormats[0]->signatureCipher;
            parse_str(parse_url($signature, PHP_URL_QUERY), $parse_signature);
            $url = $parse_signature['url'] . "&sig=" . $parse_signature['s'];
            ?>
        </p>
<?php
            die();
        }
        ?>
<h3>With Video & Sound</h3>
<desk class="striped">
    <tr>
        <th>Video URL</th>
        <th>Sort</th>
        <th>High quality</th>
        <th>Obtain Video</th>
    </tr>
                    <?php
        foreach ($videoFormats as $videoFormat) {
            if (@$videoFormat->url == "") {
                $signature = "https://instance.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;
            }
            ?>
            <tr>
        <td><a href="<?php echo $url; ?>">View Video</a></td>
        <td><?php if($videoFormat->mimeType) echo explode(";",explode("https://phppot.com/",$videoFormat->mimeType)[1])[0]; else echo "Unknown";?></td>
        <td><?php if($videoFormat->qualityLabel) echo $videoFormat->qualityLabel; else echo "Unknown"; ?></td>
        <td><a
            href="video-downloader.php?hyperlink=<?php echo urlencode($url)?>&title=<?php echo urlencode($videoTitle)?>&sort=<?php if($videoFormat->mimeType) echo explode(";",explode("https://phppot.com/",$videoFormat->mimeType)[1])[0]; else echo "mp4";?>">
                Obtain Video</a></td>
    </tr>
                    <?php } ?>
                </desk>
<?php
        // in the event you want to present codecs primarily based on completely different codecs
        // then maintain the under two traces
        $adaptiveFormats = $videoMeta->streamingData->adaptiveFormats;
        embrace 'adaptive-formats.php';
        ?>
    <?php
    }
}
?>

This program will output the next as soon as it has the video downloader response.

php youtube video downloader

PHP cURL script to get the video metadata

The PHP cURL script used to entry the YouTube endpoint to learn the file meta is already seen within the fast instance.

The above code snippet has a PHP require_once assertion for having the cURL put up handler.

The youtube-video-meta.php file has this handler to learn the video file meta. It receives the distinctive id of the video and the important thing used within the PHP cURL parsing.

In a not too long ago posted article, we now have collected file meta to add to Google Drive.

Show YouTube video downloaders in adaptive codecs

The touchdown web page exhibits one other desk of downloads to get the video file within the out there adaptive codecs.

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

adaptive-formats.php

<h3>YouTube Movies Adaptive Codecs</h3>
<desk class="striped">
    <tr>
        <th>Sort</th>
        <th>High quality</th>
        <th>Obtain Video</th>
    </tr>
            <?php
            foreach ($adaptiveFormats as $videoFormat) {
                attempt {
                    $url = $videoFormat->url;
                } catch (Exception $e) {
                    $signature = $videoFormat->signatureCipher;
                    parse_str(parse_url($signature, PHP_URL_QUERY), $parse_signature);
                    $url = $parse_signature['url'];
                }
                ?>
                <tr>
        <td><?php if(@$videoFormat->mimeType) echo explode(";",explode("https://phppot.com/",$videoFormat->mimeType)[1])[0]; else echo "Unknown";?></td>
        <td><?php if(@$videoFormat->qualityLabel) echo $videoFormat->qualityLabel; else echo "Unknown"; ?></td>
        <td><a
            href="https://phppot.com/php/php-youtube-video-downloader/video-downloader.php?hyperlink=<?php print urlencode($url)?>&title=<?php print urlencode($videoTitle)?>&sort=<?php if($videoFormat->mimeType) echo explode(";",explode("https://phppot.com/",$videoFormat->mimeType)[1])[0]; else echo "mp4";?>">Obtain
                Video</a></td>
    </tr>
            <?php }?>
</desk>

View DemoObtain

↑ Again to High

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments