You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯PHP实现个人YouTube账号视频上传问题求助

Uploading Videos to Your Own YouTube Account with Pure PHP

Hey there! Since you're working with pure PHP (no frameworks) and just need to upload videos to your own YouTube account (not building an app for others to use their accounts), let's break this down into actionable steps that play nicely with your setup.

1. Install the Google Client Library

You'll need Google's official PHP client to interact with the YouTube Data API. Even in a pure PHP project, Composer is the easiest way to manage this dependency:

composer require google/apiclient:^2.0

2. Set Up Long-Lasting OAuth 2.0 Credentials

Since this is for your own account, you don't need to handle user-facing auth flows. Instead, you can get a refresh token that lets your script authenticate indefinitely (until you revoke it):

  • Head back to your Google Cloud Console project, navigate to APIs & Services > Credentials
  • Create an OAuth client ID (select "Desktop app" as the application type—this works perfectly for server-side scripts too)
  • Download the JSON file with your client ID and client secret, save it as credentials.json in your project folder
  • Run this one-time script to generate a refresh token (run it in your terminal, not a browser):
    <?php
    require __DIR__ . '/vendor/autoload.php';
    
    $client = new Google\Client();
    $client->setAuthConfig('credentials.json');
    $client->addScope('https://www.googleapis.com/auth/youtube.upload');
    $client->setAccessType('offline'); // Ensures we get a refresh token
    
    // Generate auth URL
    $authUrl = $client->createAuthUrl();
    echo "Go to this URL and authorize your YouTube account: " . $authUrl . "\n";
    echo "Enter the authorization code you get: ";
    $authCode = trim(fgets(STDIN));
    
    // Exchange code for tokens
    $token = $client->fetchAccessTokenWithAuthCode($authCode);
    $client->setAccessToken($token);
    
    // Save the token file (store this securely—don't commit it to version control!)
    file_put_contents('token.json', json_encode($token));
    echo "Refresh token saved to token.json\n";
    ?>
    
  • Follow the link to authorize your account, paste the code back into the terminal, and you'll get a token.json file with your long-lasting refresh token.

3. Write the Video Upload Script

Here's a complete, working example that handles uploading a video with custom metadata:

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

// Initialize Google Client
$client = new Google\Client();
$client->setAuthConfig('credentials.json');
$client->addScope('https://www.googleapis.com/auth/youtube.upload');
$client->setAccessToken(file_get_contents('token.json'));

// Refresh token if it's expired
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents('token.json', json_encode($client->getAccessToken()));
}

// Create YouTube service instance
$youtube = new Google\Service\YouTube($client);

// Define video metadata
$video = new Google\Service\YouTube\Video();
$videoSnippet = new Google\Service\YouTube\VideoSnippet();
$videoSnippet->setTitle("My Pure PHP Uploaded Video");
$videoSnippet->setDescription("Uploaded directly from my pure PHP script");
$videoSnippet->setTags(["PHP", "YouTube API", "Self-Upload"]);
$video->setSnippet($videoSnippet);

// Set video privacy status (public/private/unlisted)
$videoStatus = new Google\Service\YouTube\VideoStatus();
$videoStatus->setPrivacyStatus("private"); // Adjust this as needed
$video->setStatus($videoStatus);

// Prepare media upload
$videoPath = '/path/to/your/video.mp4'; // Replace with your actual video file path
$media = new Google\Http\MediaFileUpload(
    $client,
    $youtube->videos->insert("snippet,status", $video),
    'video/*',
    file_get_contents($videoPath)
);
$media->setChunkSize(Google\Http\MediaFileUpload::DEFAULT_CHUNK_SIZE);

// Perform the upload
$status = false;
$handle = fopen($videoPath, 'rb');
while (!$status && !feof($handle)) {
    $chunk = fread($handle, $media->getChunkSize());
    $status = $media->nextChunk($chunk);
}

fclose($handle);

// Check upload result
if ($status->id) {
    echo "Success! Your video ID is: " . $status->id . "\n";
} else {
    echo "Upload failed. Double-check your file path and credentials.\n";
}
?>

Quick Tips to Avoid Headaches

  • File Permissions: Make sure your PHP script has read access to the video file and write access to update token.json.
  • PHP Extensions: Enable curl and openssl in your PHP config—they're required for the Google client to communicate with the API.
  • Video Specs: Stick to MP4 format (it's the most reliable for YouTube) and ensure your file meets YouTube's size/encoding requirements.
  • Security: Keep credentials.json and token.json locked down—never expose them publicly or commit them to Git.

内容的提问来源于stack exchange,提问作者davidesp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:14:33