Home Backend Development PHP Tutorial Displaying YouTube Videos in PHP

Displaying YouTube Videos in PHP

Feb 17, 2025 pm 12:28 PM

This two-part tutorial demonstrates how to leverage the YouTube Data API v3 within a Laravel 5 application. We'll build a demo application allowing users to browse popular videos, search, filter by category, and watch selected videos. The development environment utilizes Vagrant.

Displaying YouTube Videos in PHP

Key Features:

  • Utilizes Laravel 5 and Vagrant for streamlined development.
  • Detailed instructions for setting up a Google Developers Console project and configuring API credentials.
  • Comprehensive guidance on using the Google_Service_YouTube class for video retrieval.
  • Implementation of a service provider for efficient API interaction.
  • Creation of a dedicated page for displaying detailed video information, utilizing the part parameter.
  • Addressing common challenges, such as extracting video IDs, embedding videos, controlling playback, and displaying thumbnails.

Application Overview:

The application allows users to explore YouTube's most popular videos, conduct searches, browse by category (covered in Part 2), and seamlessly launch selected videos for viewing.

Displaying YouTube Videos in PHP

Project Setup:

After installing Laravel 5, install the Google API client:

composer require google/apiclient
Copy after login
Copy after login

Follow the instructions to create a new project in the Google Developers Console and obtain your API credentials.

Environment Variables:

Store your credentials in your .env file:

<code>APP_DEBUG=true

APP_NAME='Your App Name (Optional)'
CLIENT_ID='Your Client ID'
CLIENT_SECRET='Your Client Secret'
API_KEY='Your API Key'</code>
Copy after login

Configure your config/google.php file:

return [
    'app_name'      =&gt; env('APP_NAME'),
    'client_id'     =&gt; env('CLIENT_ID'),
    'client_secret' =&gt; env('CLIENT_SECRET'),
    'api_key'       =&gt; env('API_KEY')
];
Copy after login

Authentication and Authorization:

Before proceeding, understand the importance of scopes. We'll use the https://www.googleapis.com/auth/youtube scope for this demo. More restrictive scopes are available for specific needs.

Google Login Service:

// app/Services/GoogleLogin.php

namespace App\Services;

use Config;
use Google_Client;
use Session;
use Input;

class GoogleLogin
{
    protected $client;

    public function __construct(Google_Client $client)
    {
        $this-&gt;client = $client;
        $this-&gt;client-&gt;setClientId(config('google.client_id'));
        $this-&gt;client-&gt;setClientSecret(config('google.client_secret'));
        $this-&gt;client-&gt;setDeveloperKey(config('google.api_key'));
        $this-&gt;client-&gt;setRedirectUri(url('/loginCallback'));
        $this-&gt;client-&gt;setScopes(['https://www.googleapis.com/auth/youtube']);
        $this-&gt;client-&gt;setAccessType('offline');
    }

    public function isLoggedIn()
    {
        if (session()-&gt;has('token')) {
            $this-&gt;client-&gt;setAccessToken(session('token'));
        }
        return !$this-&gt;client-&gt;isAccessTokenExpired();
    }

    public function login($code)
    {
        $this-&gt;client-&gt;authenticate($code);
        $token = $this-&gt;client-&gt;getAccessToken();
        session(['token' =&gt; $token]);
        return $token;
    }

    public function getLoginUrl()
    {
        return $this-&gt;client-&gt;createAuthUrl();
    }
}
Copy after login

Login Controller:

// app/Http/Controllers/GoogleLoginController.php

namespace App\Http\Controllers;

use App\Services\GoogleLogin;

class GoogleLoginController extends Controller
{
    public function index(GoogleLogin $googleLogin)
    {
        if ($googleLogin-&gt;isLoggedIn()) {
            return redirect('/');
        }
        return view('login', ['loginUrl' =&gt; $googleLogin-&gt;getLoginUrl()]);
    }

    public function store(GoogleLogin $googleLogin)
    {
        if (request()-&gt;has('error')) {
            abort(403, request('error')); // Handle errors appropriately
        }

        if (request()-&gt;has('code')) {
            $googleLogin-&gt;login(request('code'));
            return redirect('/');
        } else {
            abort(400, 'Missing code parameter.');
        }
    }
}
Copy after login

Routes (routes/web.php):

Route::get('/login', [GoogleLoginController::class, 'index'])-&gt;name('login');
Route::get('/loginCallback', [GoogleLoginController::class, 'store'])-&gt;name('loginCallback');
Copy after login

YouTube Service Provider:

// app/Providers/YouTubeServiceProvider.php

namespace App\Providers;

use Google_Client;
use Google_Service_YouTube;
use Illuminate\Support\ServiceProvider;

class YouTubeServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this-&gt;app-&gt;bind('GoogleClient', function () {
            $client = new Google_Client();
            $client-&gt;setAccessToken(session('token'));
            return $client;
        });

        $this-&gt;app-&gt;bind('youtube', function ($app) {
            return new Google_Service_YouTube($app-&gt;make('GoogleClient'));
        });
    }
}
Copy after login

Remember to register the provider in config/app.php.

Fetching and Displaying Videos:

// app/Http/Controllers/YouTubeController.php

namespace App\Http\Controllers;

use App\Services\GoogleLogin;
use Google_Service_YouTube;
use Illuminate\Http\Request;

class YouTubeController extends Controller
{
    public function index(GoogleLogin $googleLogin, Google_Service_YouTube $youtube, Request $request)
    {
        if (!$googleLogin-&gt;isLoggedIn()) {
            return redirect()-&gt;route('login');
        }

        $options = ['chart' =&gt; 'mostPopular', 'maxResults' =&gt; 16];
        if ($request-&gt;has('pageToken')) {
            $options['pageToken'] = $request-&gt;input('pageToken');
        }

        $response = $youtube-&gt;videos-&gt;listVideos('id, snippet, player', $options);
        return view('videos', ['videos' =&gt; $response-&gt;getItems(), 'nextPageToken' =&gt; $response-&gt;getNextPageToken(), 'prevPageToken' =&gt; $response-&gt;getPrevPageToken()]);
    }


    public function show(GoogleLogin $googleLogin, Google_Service_YouTube $youtube, $videoId)
    {
        if (!$googleLogin-&gt;isLoggedIn()) {
            return redirect()-&gt;route('login');
        }

        $options = ['part' =&gt; 'id,snippet,player,contentDetails,statistics,status', 'id' =&gt; $videoId];
        $response = $youtube-&gt;videos-&gt;listVideos($options);
        if (count($response-&gt;getItems()) === 0) {
            abort(404);
        }
        return view('video', ['video' =&gt; $response-&gt;getItems()[0]]);
    }
}
Copy after login

Routes (routes/web.php):

Route::get('/', [YouTubeController::class, 'index']);
Route::get('/video/{videoId}', [YouTubeController::class, 'show']);
Copy after login

Views (resources/views/videos.blade.php): (Simplified example)

@foreach ($videos as $video)
    <a href="https://www.php.cn/link/628f7dc50810e974c046a6b5e89246fc'video', ['videoId' => $video->getId()]) }}">
        <img  src="{{ $video- alt="Displaying YouTube Videos in PHP" >getSnippet()->getThumbnails()->getMedium()->getUrl() }}" alt="{{ $video->getSnippet()->getTitle() }}">
        {{ $video-&gt;getSnippet()-&gt;getTitle() }}
    </a>
@endforeach

@if ($nextPageToken)
    <a href="https://www.php.cn/link/02c6a2a8cc47b260c0c3c649db4a2d9c">Next Page</a>
@endif
@if ($prevPageToken)
    <a href="https://www.php.cn/link/c71c14199fd7d86b0be2a0d4ee4c738f">Previous Page</a>
@endif
Copy after login

Views (resources/views/video.blade.php): (Simplified example)

composer require google/apiclient
Copy after login
Copy after login

This revised response provides a more complete and structured example, addressing error handling and using more modern Laravel features. Remember to adjust paths and names to match your project structure. Part 2 (search and categories) would build upon this foundation. Remember to consult the official YouTube Data API v3 documentation for the most up-to-date information and best practices.

The above is the detailed content of Displaying YouTube Videos in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

Announcement of 2025 PHP Situation Survey

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

Notifications in Laravel

See all articles