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'      => env('APP_NAME'),
    'client_id'     => env('CLIENT_ID'),
    'client_secret' => env('CLIENT_SECRET'),
    'api_key'       => 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->client = $client;
        $this->client->setClientId(config('google.client_id'));
        $this->client->setClientSecret(config('google.client_secret'));
        $this->client->setDeveloperKey(config('google.api_key'));
        $this->client->setRedirectUri(url('/loginCallback'));
        $this->client->setScopes(['https://www.googleapis.com/auth/youtube']);
        $this->client->setAccessType('offline');
    }

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

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

    public function getLoginUrl()
    {
        return $this->client->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->isLoggedIn()) {
            return redirect('/');
        }
        return view('login', ['loginUrl' => $googleLogin->getLoginUrl()]);
    }

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

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

Routes (routes/web.php):

Route::get('/login', [GoogleLoginController::class, 'index'])->name('login');
Route::get('/loginCallback', [GoogleLoginController::class, 'store'])->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->app->bind('GoogleClient', function () {
            $client = new Google_Client();
            $client->setAccessToken(session('token'));
            return $client;
        });

        $this->app->bind('youtube', function ($app) {
            return new Google_Service_YouTube($app->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->isLoggedIn()) {
            return redirect()->route('login');
        }

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

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


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

        $options = ['part' => 'id,snippet,player,contentDetails,statistics,status', 'id' => $videoId];
        $response = $youtube->videos->listVideos($options);
        if (count($response->getItems()) === 0) {
            abort(404);
        }
        return view('video', ['video' => $response->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->getSnippet()->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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles