YouTube API: Upload Videos With PHP - Step-by-Step Guide

by Admin 57 views
YouTube API: Upload Videos with PHP - Step-by-Step Guide

So, you want to automate your video uploads to YouTube using PHP? Awesome! You've come to the right place. In this comprehensive guide, we'll walk you through the entire process, step by step. We will cover everything from setting up your Google Cloud project to writing the PHP code that handles the upload. Get ready to unleash the power of the YouTube API and streamline your video workflow, guys! This tutorial assumes you have a basic understanding of PHP and some familiarity with APIs in general. If you're completely new to these concepts, it might be helpful to brush up on them before diving in. Let’s start this exciting journey to make our lives easier and more efficient.

Prerequisites

Before we get our hands dirty with the code, let's make sure we have all the necessary tools and accounts set up. This section is crucial, so don't skip it!

  1. Google Account: You'll need a Google account, obviously. If you don't have one already, sign up for free. This account will be used to access the Google Cloud Console and manage your YouTube channel.
  2. Google Cloud Project: A Google Cloud project is where you'll enable the YouTube Data API and create the credentials needed for authentication. We'll walk through this process in detail in the next section.
  3. PHP Environment: You'll need a PHP environment set up on your local machine or server. This includes PHP itself, a web server (like Apache or Nginx), and the composer package manager. Make sure your PHP version is compatible with the YouTube API client library. I recommend using PHP 7.4 or higher.
  4. Composer: Composer is a dependency management tool for PHP. We'll use it to install the Google API client library and its dependencies. If you don't have Composer installed, download and install it from https://getcomposer.org/.
  5. YouTube Channel: Of course, you'll need a YouTube channel where you want to upload the videos. If you don't have one yet, create one through your Google account.

Once you have all these prerequisites in place, you're ready to move on to the next step: setting up your Google Cloud project.

Setting Up Your Google Cloud Project

Okay, guys, now let's dive into the Google Cloud Console and configure our project. This might seem a bit daunting at first, but trust me, it's not that complicated. Just follow these steps carefully, and you'll be fine.

  1. Access Google Cloud Console: Go to the Google Cloud Console at https://console.cloud.google.com/ and log in with your Google account.
  2. Create a New Project: If you don't have an existing project, create a new one. Click on the project selection dropdown at the top of the page and then click "New Project." Give your project a meaningful name (e.g., "YouTube Uploader") and select an organization if applicable. Then, click "Create."
  3. Enable the YouTube Data API v3: Once your project is created, you need to enable the YouTube Data API v3. In the Cloud Console, navigate to "APIs & Services" > "Library." Search for "YouTube Data API v3" and click on it. Then, click the "Enable" button. This API allows you to programmatically interact with YouTube, including uploading videos.
  4. Create Credentials: Now, we need to create credentials to authenticate our PHP application with the YouTube API. Go to "APIs & Services" > "Credentials." Click on "Create Credentials" and select "OAuth client ID." You might be prompted to configure the consent screen first. If so, click "Configure consent screen" and fill out the required information (e.g., application name, support email). Choose "External" for the user type and click "Create."
  5. Configure OAuth Client ID: On the "Create OAuth client ID" page, select "Web application" as the application type. Give your client ID a name (e.g., "YouTube Uploader Client"). In the "Authorized JavaScript origins" field, enter the URL of your PHP application (e.g., http://localhost if you're running it locally). In the "Authorized redirect URIs" field, enter the URL where Google will redirect the user after they grant your application access to their YouTube account (e.g., http://localhost/oauth2callback.php). You'll need to create this oauth2callback.php file later. Click "Create."
  6. Download Credentials: After creating the OAuth client ID, you'll see a popup with your client ID and client secret. Important: Download these credentials as a JSON file by clicking the download icon next to the client ID. Save this file in a secure location, as you'll need it in your PHP code. Keep this file safe and don't share it publicly! I usually rename this file client_secret.json.

With these steps completed, your Google Cloud project is now properly set up to work with the YouTube Data API. Now comes the fun part: writing the PHP code!

Installing the Google API Client Library

Before writing any code, we need to install the Google API client library for PHP. This library provides the necessary classes and functions to interact with the YouTube API. We'll use Composer to install it. This is a crucial step! Open your terminal or command prompt, navigate to the root directory of your PHP project, and run the following command:

composer require google/apiclient:^2.0

This command will download and install the Google API client library and its dependencies into your project's vendor directory. Make sure the process completes without any errors. If you encounter any issues, double-check that you have Composer installed correctly and that your PHP environment is properly configured.

Once the installation is complete, you'll have a vendor directory in your project containing all the necessary files. You can now include these files in your PHP scripts using Composer's autoloader.

Writing the PHP Code

Alright, folks, let's get to the heart of the matter: writing the PHP code to upload videos to YouTube. We'll break this down into several steps, creating separate files for different functionalities.

1. client.php (Authentication and Client Setup)

This file will handle the authentication process and create a Google API client instance. Here's the code:

<?php
require_once __DIR__ . '/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setApplicationName('YouTube Uploader');
$client->setScopes([Google_Service_YouTube::YOUTUBE_UPLOAD, Google_Service_YouTube::YOUTUBE]);
$client->setAuthConfig('client_secret.json');
$client->setAccessType('offline');

// Define callback URL
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
$client->setRedirectUri($redirect_uri);

// Handle authorization flow
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->fetchAccessTokenWithAuthCode($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  header('Location: ./');
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
}

// Check to see if access token has expired.
if ($client->isAccessTokenExpired()) {
    unset($_SESSION['access_token']);
}

return $client;

Explanation:

  • We require the Composer autoloader to load the Google API client library.
  • We start a session to store the access token.
  • We create a Google_Client instance and configure it with our application name, scopes (permissions), and client secret file.
  • We set the access type to offline to get a refresh token, allowing us to upload videos even when the user is not present.
  • We define the redirect URI and set it on the client.
  • We handle the authorization flow: if the user hasn't granted access yet, we redirect them to Google's authorization page. After granting access, Google redirects the user back to our oauth2callback.php file with an authorization code.
  • We exchange the authorization code for an access token and store it in the session.
  • Lastly, we check the access token. If this exists in our session then we want to use it. Or if this is expired we want to unset it from our session.

2. oauth2callback.php (OAuth 2.0 Callback)

This file handles the OAuth 2.0 callback from Google after the user grants your application access to their YouTube account. Here's the code:

<?php
require_once __DIR__ . '/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setApplicationName('YouTube Uploader');
$client->setAuthConfig('client_secret.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->setAccessType('offline');
$client->setScopes([Google_Service_YouTube::YOUTUBE_UPLOAD, Google_Service_YouTube::YOUTUBE]);

if (! isset($_GET['code'])) {
  header('Location: /');
  exit;
}

$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ./');

Explanation:

  • We require the Composer autoloader and start a session.
  • We create a Google_Client instance and configure it similarly to client.php.
  • We check for the authorization code in the $_GET array. If it's not present, we redirect the user back to the main page.
  • We exchange the authorization code for an access token and store it in the session.
  • Finally, we redirect the user back to the main page.

3. upload.php (Video Upload Logic)

This file contains the core logic for uploading videos to YouTube. Here's the code:

<?php
require_once __DIR__ . '/vendor/autoload.php';

function uploadVideo($client, $videoPath, $title, $description, $keywords, $categoryId) {
    $youtube = new Google_Service_YouTube($client);

    $video = new Google_Service_YouTube_Video();
    $video->setSnippet(array(
        'title' => $title,
        'description' => $description,
        'tags' => explode(',', $keywords),
        'categoryId' => $categoryId
    ));

    $video->setStatus(array(
        'privacyStatus' => 'private' // or 'public', 'unlisted'
    ));

    // Chunk size of 1MB - make it configurable
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Setting the defer flag to true tells the client to return a request which can be called
    // with ->execute(); instead of making the API call immediately.
    $client->setDefer(true);

    // Create a request for the API endpoint to insert video into media library
    $insertRequest = $youtube->videos->insert("snippet,status", $video, array(
        'data' => file_get_contents($videoPath),
        'mimeType' => 'application/octet-stream'
    ));

    // Upload the video in chunks.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $insertRequest,
        'application/octet-stream',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($videoPath));


    $status = false;
    try {
        while (!$status && !feof(fopen($videoPath, 'rb'))) {
            $status = $media->nextChunk();
        }
    
        // If you want to make other calls after the file upload, set setDefer back to false
        $client->setDefer(false);
    
        return $status['id'];
    } catch (Google_Service_Exception $e) {
        echo '<p>A service error occurred: <code>' . htmlspecialchars($e->getMessage()) . '</code></p>';
    } catch (Exception $e) {
        echo '<p>An client error occurred: <code>' . htmlspecialchars($e->getMessage()) . '</code></p>';
    }

    return false;
}

Explanation:

  • We require the Composer autoloader.
  • We define an uploadVideo function that takes the Google API client, video path, title, description, keywords, and category ID as arguments.
  • We create a Google_Service_YouTube instance.
  • We create a Google_Service_YouTube_Video instance and set its snippet (metadata) and status (privacy).
  • We set the chunk size for uploading the video in chunks.
  • We create an insert request to upload the video.
  • We create a Google_Http_MediaFileUpload instance to handle the chunked upload.
  • We upload the video in chunks using a while loop.
  • If successful, we return the video ID. Otherwise, we return false.

4. index.php (Main Page)

This is the main page of your application where users can authenticate and upload videos. Here's a basic example:

<?php
session_start();

require_once __DIR__ . '/client.php';

if (!$client->isAccessTokenExpired()) {
    echo '<form action="upload_process.php" method="post" enctype="multipart/form-data">';
    echo 'Select video to upload:';
    echo '<input type="file" name="video" id="video">';
    echo '<br>';
    echo 'Title: <input type="text" name="title"><br>';
    echo 'Description: <textarea name="description"></textarea><br>';
    echo 'Keywords: <input type="text" name="keywords"><br>';
    echo 'Category ID: <input type="text" name="categoryId" value="22"><br>'; // 22 is People & Blogs
    echo '<input type="submit" value="Upload Video" name="submit">';
    echo '</form>';
} else {
    echo '<a href="' . filter_var($client->createAuthUrl(), FILTER_SANITIZE_URL) . '">Login to YouTube</a>';
}
?>

Explanation:

  • We start a session and include the client.php file.
  • We check if the user is authenticated (access token exists and is not expired).
  • If authenticated, we display a form for uploading videos. The form includes fields for the video file, title, description, keywords, and category ID.
  • If not authenticated, we display a link to log in to YouTube.

5. upload_process.php (Handling Form Submission)

This file handles the form submission from index.php and calls the uploadVideo function to upload the video. Here's the code:

<?php
session_start();
require_once __DIR__ . '/client.php';
require_once __DIR__ . '/upload.php';

if (isset($_POST['submit'])) {
    $videoPath = $_FILES['video']['tmp_name'];
    $title = $_POST['title'];
    $description = $_POST['description'];
    $keywords = $_POST['keywords'];
    $categoryId = $_POST['categoryId'];

    $videoId = uploadVideo($client, $videoPath, $title, $description, $keywords, $categoryId);

    if ($videoId) {
        echo 'Video uploaded successfully! Video ID: ' . $videoId;
    } else {
        echo 'Video upload failed.';
    }
}
?>

Explanation:

  • We start a session and include the client.php and upload.php files.
  • We check if the form has been submitted.
  • We retrieve the video file path, title, description, keywords, and category ID from the $_POST array.
  • We call the uploadVideo function to upload the video.
  • We display a success or failure message based on the result.

Running the Application

Now that we have all the code in place, let's run the application.

  1. Place all the PHP files (client.php, oauth2callback.php, upload.php, index.php, upload_process.php) and the client_secret.json file in the root directory of your PHP project.
  2. Make sure your web server is configured to serve the files from this directory.
  3. Open your web browser and navigate to the URL of your index.php file (e.g., http://localhost/index.php).
  4. If you're not already logged in to YouTube, you'll be prompted to log in and grant your application access to your account. Click "Allow" to grant access.
  5. After granting access, you'll be redirected back to the index.php page.
  6. You can now select a video file, enter the title, description, keywords, and category ID, and click "Upload Video" to upload the video to your YouTube channel.

Conclusion

Congratulations, mate! You've successfully built a PHP application to upload videos to YouTube using the YouTube API. This is a powerful tool that can save you a lot of time and effort. Now you can automate your video uploads and focus on creating great content.

Remember to handle errors properly, validate user input, and secure your application to protect your users and your data. You can extend this application further by adding features like progress tracking, scheduled uploads, and more.

I hope this guide has been helpful. If you have any questions or run into any issues, feel free to ask in the comments below. Happy coding, guys!