CODE SNIPPET - Come scaricare video da Youtube con php

 Voglio aprire questa sezione del blog con un code snippet che può interessare parecchi ragazzi che smanettano con il Php.


Oggi ti mostrerò che come scaricare video di YouTube utilizzando PHP con una classe PHP disponibile qui.
Un tutorial molto semplice e facile da integrare
.

Iniziamo

Codice sorgente inerente alla libreria per scaricare i files Youtube.

<?php
/**
* andrea tamburelli
*
* @class YouTubeDownloader
* @author Andrea Tamburelli
*
*/
Class YouTubeDownloader {
/** * Get the YouTube code from a video URL * @param $url * @return mixed */
* Get the YouTube code from a video URL
* @param $url
* @return mixed
*/
public function getYouTubeCode($url) {
parse_str( parse_url( $url, PHP_URL_QUERY ), $vars );
return $vars['v'];
}
/** * Process the video url and return details of the video * @param $vid * @return array|void */
* Process the video url and return details of the video
* @param $vid
* @return array|void
*/
public function processVideo($vid) {
parse_str(file_get_contents("https://youtube.com/get_video_info?video_id=".$vid),$info);
$playabilityJson = json_decode($info['player_response']);
$formats = $playabilityJson->streamingData->formats;
$adaptiveFormats = $playabilityJson->streamingData->adaptiveFormats;
//Checking playable or not
$IsPlayable = $playabilityJson->playabilityStatus->status;
//writing to log file
if(strtolower($IsPlayable) != 'ok') {
$log = date("c")." ".$info['player_response']."\n";
file_put_contents('./video.log', $log, FILE_APPEND);
}
$result = array();
if(!empty($info) && $info['status'] == 'ok' && strtolower($IsPlayable) == 'ok') {
$i=0;
foreach($adaptiveFormats as $stream) {
$streamUrl = $stream->url;
$type = explode(";", $stream->mimeType);
$qualityLabel='';
if(!empty($stream->qualityLabel)) {
$qualityLabel = $stream->qualityLabel;
}
$videoOptions[$i]['link'] = $streamUrl;
$videoOptions[$i]['type'] = $type[0];
$videoOptions[$i]['quality'] = $qualityLabel;
$i++;
}
$j=0;
foreach($formats as $stream) {
$streamUrl = $stream->url;
$type = explode(";", $stream->mimeType);
$qualityLabel='';
if(!empty($stream->qualityLabel)) {
$qualityLabel = $stream->qualityLabel;
}
$videoOptionsOrg[$j]['link'] = $streamUrl;
$videoOptionsOrg[$j]['type'] = $type[0];
$videoOptionsOrg[$j]['quality'] = $qualityLabel;
$j++;
}
$result['videos'] = array(
'info'=>$info,
'adapativeFormats'=>$videoOptions,
'formats'=>$videoOptionsOrg
);
return $result;
}
else {
return;
}
}
}

Nella funzione, prima facciamo il parsing degli output dalla pagina di informazioni video di YouTube.
Successivamente, controlliamo lo stato per vedere se è ok, per passare poi agli step successivi di analisi dei diversi flussi utilizzando questo codice .
processVideo()$playabilityJson->streamingData->adaptiveFormats

La classe restituirà diverse versioni di video di YouTube come mp4, mp3 e soprattutto varie qualità(720p,360p).
Infine, si spingono tutti questi in una matrice e impostare il valore in cambio.

 Scarichiamo il video di YouTube utilizzando un semplice modulo in PHP

Usiamo il seguente modulo per prendere gli utenti input ie. URL video di YouTube. Questo è disponibile nel file .index.php

<form method="post" action="" class="formSmall">
<div class="row">
<div class="col-lg-12">
<h7 class="text-align"> Download YouTube Video</h7>
</div>
<div class="col-lg-12">
<div class="input-group">
<input type="text" class="form-control" name="video_link" placeholder="Paste link.. e.g. https://www.youtube.com/watch?v=OK_JCtrrv-c">
<span class="input-group-btn">
<button type="submit" name="submit" id="submit" class="btn btn-primary">Go!</button>
</span>
</div><!-- /input-group -->
</div>
</div><!-- .row -->
</form>

Successivamente, dobbiamo scrivere il nostro codice PHP che immette l'ID video e restituire i diversi URL video per il download.

<?php
require_once "class.youtube.php";
$yt  = new YouTubeDownloader();
$downloadLinks ='';
$error='';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $videoLink = $_POST['video_link'];
    if(!empty($videoLink)) {
        $vid = $yt->getYouTubeCode($videoLink);
        if($vid) {
            $result = $yt->processVideo($vid);
            
            if($result) {
                //print_r($result);
                $info = $result['videos']['info'];
                $formats = $result['videos']['formats'];
                $adapativeFormats = $result['videos']['adapativeFormats'];

                

                $videoInfo = json_decode($info['player_response']);

                $title = $videoInfo->videoDetails->title;
                $thumbnail = $videoInfo->videoDetails->thumbnail->thumbnails{0}->url;
            }
            else {
                $error = "Something went wrong";
            }

        }
    }
    else {
        $error = "Please enter a YouTube video URL";
    }
}
?>

Nel codice sopra, includiamo il file di classe , che è il nucleo di questa applicazione.
Infine, viene confermato il metodo POST e recuperariamo i risultati dai metodi della classe.
class.youtube.php

Il codice seguente ti mostrerà come visualizzare i link di download di YouTube in un formato tabulare, con qualità e tipo.

<?php if($formats):?>
        <div class="row formSmall">
            <div class="col-lg-3">
                <img src="<?php print $thumbnail?>">
            </div>
            <div class="col-lg-9">
                <?php print $title?>
            </div>
        </div>

        <div class="card formSmall">
            <div class="card-header">
                <strong>With Video & Sound</strong>
            </div>
            <div class="card-body">
                <table class="table ">
                    <tr>
                        <td>Type</td>
                        <td>Quality</td>
                        <td>Download</td>
                    </tr>
                    <?php foreach ($formats as $video) :?>
                        <tr>
                            <td><?php print $video['type']?></td>
                            <td><?php print $video['quality']?></td>
                            <td><a href="downloader.php?link=<?php print urlencode($video['link'])?>&title=<?php print urlencode($title)?>&type=<?php print urlencode($video['type'])?>">Download</a> </td>
                        </tr>
                    <?php endforeach;?>
                </table>
            </div>
        </div>

        <div class="card formSmall">
            <div class="card-header">
                <strong>Videos video only/ Audios audio only</strong>
            </div>
            <div class="card-body">
                <table class="table ">
                    <tr>
                        <td>Type</td>
                        <td>Quality</td>
                        <td>Download</td>
                    </tr>
                    <?php foreach ($adapativeFormats as $video) :?>
                        <tr>
                            <td><?php print $video['type']?></td>
                            <td><?php print $video['quality']?></td>
                            <td><a href="downloader.php?link=<?php print urlencode($video['link'])?>&title=<?php print urlencode($title)?>&type=<?php print urlencode($video['type'])?>">Download</a> </td>
                        </tr>
                    <?php endforeach;?>
                </table>
            </div>
        </div>
        <?php endif;?>

Come scaricare il video utilizzando il link?

Avrete notato che c'è una pagina richiamata nello script di cui sopra.
Questo script si occupa del download forzato del file sul computer o sul cellulare.
Questo è il processo di download forzato in PHP.
downloader.php


<?
php $downloadURL = urldecode($_GET['link']); //print $downloadURL;exit; $type = urldecode($_GET['type']); $title = urldecode($_GET['title']); //Finding file extension from the mime type $typeArr = explode("/",$type); $extension = $typeArr[1]; $fileName = $title.'.'.$extension; if (!empty($downloadURL)) { header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment;filename=\"$fileName\""); header("Content-Transfer-Encoding: binary"); readfile($downloadURL); }

Commenti