Skrip Pengunduh Video YouTube PHP

0
(0)

oleh Vincy. Terakhir diubah pada 15 September 2022.

YouTube hampir merupakan platform numero uno untuk meng-hosting video. Ini memungkinkan pengguna untuk mempublikasikan dan berbagi video, lebih seperti jejaring sosial.

Mengunduh video YouTube terkadang diperlukan. Anda harus membaca syarat dan ketentuan YouTube sebelum mengunduh video dan bertindak sesuai dengan izin yang diberikan. Misalnya, Anda mungkin ingin mengunduh untuk memiliki cadangan video lama yang akan diganti atau dihapus.

Contoh singkat ini menyediakan skrip pengunduh Video YouTube dalam PHP. Ini memiliki URL video yang didefinisikan dalam variabel PHP. Itu juga menetapkan kunci untuk mengakses meta video YouTube melalui API.

Konfigurasikan kuncinya dan simpan URL video untuk mendapatkan tautan pengunduh video menggunakan skrip ini.

Contoh cepat

<?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->formats;
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?link=<?php echo urlencode($url)?>&title=<?php echo urlencode($videoTitle)?>&type=<?php echo $mimeType; ?>">
    Download Video</a>
<?php
}

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="{"context": {"client": {"hl": "en","clientName": "WEB",
        "clientVersion": "2.20210721.00.00","clientFormFactor": "UNKNOWN_FORM_FACTOR","clientScreen": "WATCH",
        "mainAppWebInfo": {"graftUrl": "/watch?v=" . $videoId . '",}},"user": {"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-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;
}
?>

Kode contoh ini berfungsi dalam alur berikut untuk menampilkan tautan untuk mengunduh video YouTube.

  1. Dapatkan id unik video YouTube dari URL masukan.
  2. Minta API YouTube melalui pos PHP cURL untuk mengakses metadata video.
  3. Dapatkan judul video, larik data dalam berbagai format, dan tipe MIME dengan mem-parsing respons cURL.
  4. Berikan tautan video, judul, dan jenis pantomim ke skrip pengunduh video.
  5. Terapkan PHP file baca() untuk mengunduh file video dengan mengatur header PHP Jenis konten.

tautan pengunduh video youtube php

Skrip pengunduh video di bawah ini dipanggil dengan mengklik tautan “Unduh video” di browser.

Ini menerima judul video, dan ekstensi untuk menentukan nama file video output. Itu juga mendapatkan tautan video dari mana ia membaca video untuk diunduh ke browser.

Skrip ini mengatur header konten dalam PHP untuk menampilkan file video YouTube.

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-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment;filename="$downloadFileName"");
    header("Content-Transfer-Encoding: binary");
    readfile($downloadURL);
}
?>

Lihat Demo

Kumpulkan URL video YouTube melalui formulir dan proses skrip pengunduh video

Dalam contoh singkat, ia memiliki contoh untuk membuat hardcode URL video YouTube ke variabel PHP.

Tapi, kode di bawah ini akan memungkinkan pengguna untuk memasukkan URL video, bukan hardcode.

Formulir HTML akan memposting URL video yang dimasukkan untuk memproses permintaan PHP cURL ke API YouTube.

Setelah memposting URL video, alur PHP sama dengan contoh cepat. Namun, perbedaannya adalah, ini menampilkan lebih banyak tautan untuk mengunduh video dalam semua format adaptif.

index.php

<form method="post" action="">
    <h1>PHP YouTube Video Downloader Script</h1>
    <div class="row">
        <input type="text" class="inline-block" name="youtube-video-url">
        <button type="submit" name="submit" id="submit">Download Video</button>
    </div>
</form>
<?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 = end($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->formats;
    if (! empty($videoFormats)) {
        if (@$videoFormats[0]->url == "") {
            ?>
<p>
    <strong>This YouTube video cannot be downloaded by the downloader!</strong><?php
            $signature = "https://example.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>
<table class="striped">
    <tr>
        <th>Video URL</th>
        <th>Type</th>
        <th>Quality</th>
        <th>Download Video</th>
    </tr>
                    <?php
        foreach ($videoFormats as $videoFormat) {
            if (@$videoFormat->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;
            }
            ?>
            <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?link=<?php echo urlencode($url)?>&title=<?php echo urlencode($videoTitle)?>&type=<?php if($videoFormat->mimeType) echo explode(";",explode("https://phppot.com/",$videoFormat->mimeType)[1])[0]; else echo "mp4";?>">
                Download Video</a></td>
    </tr>
                    <?php } ?>
                </table>
<?php
        // if you wish to provide formats based on different formats
        // then keep the below two lines
        $adaptiveFormats = $videoMeta->streamingData->adaptiveFormats;
        include 'adaptive-formats.php';
        ?>
    <?php
    }
}
?>

Program ini akan menampilkan yang berikut setelah mendapat respons pengunduh video.

pengunduh video youtube php

Skrip PHP cURL untuk mendapatkan metadata video

Skrip PHP cURL yang digunakan untuk mengakses titik akhir YouTube untuk membaca meta file sudah terlihat dalam contoh cepat.

Cuplikan kode di atas memiliki pernyataan PHP require_once untuk memiliki pengendali posting cURL.

Itu youtube-video-meta.php file memiliki handler ini untuk membaca meta file video. Ini menerima id unik dari video dan kunci yang digunakan dalam parsing PHP cURL.

Dalam artikel yang baru-baru ini diposting, kami telah mengumpulkan meta file untuk diunggah ke Google Drive.

Tampilkan pengunduh video YouTube dalam format adaptif

Halaman arahan menunjukkan tabel unduhan lain untuk mendapatkan file video dalam format adaptif yang tersedia.

Skrip PHP mengakses format adaptif properti dari meta-objek video Youtube untuk menampilkan unduhan ini.

adaptif-formats.php

<h3>YouTube Videos Adaptive Formats</h3>
<table class="striped">
    <tr>
        <th>Type</th>
        <th>Quality</th>
        <th>Download Video</th>
    </tr>
            <?php
            foreach ($adaptiveFormats as $videoFormat) {
                try {
                    $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?link=<?php print urlencode($url)?>&title=<?php print urlencode($videoTitle)?>&type=<?php if($videoFormat->mimeType) echo explode(";",explode("https://phppot.com/",$videoFormat->mimeType)[1])[0]; else echo "mp4";?>">Download
                Video</a></td>
    </tr>
            <?php }?>
</table>

Lihat DemoUnduh

Kembali ke Atas


Source link

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.