How to upload videos to YouTube with PHP using YouTube Data API v3

I’m having trouble uploading videos to YouTube through PHP code. I’m working with the YouTube Data API v3 and the Google API PHP Client library from their official repository.

The OAuth authentication part works perfectly fine, but when I attempt to upload a video file, I keep getting a Google_ServiceException error with status code 500 and an empty error message.

I’ve tried setting the categoryId in the video snippet since I read somewhere that it might be required. I also implemented a retry loop for 500-level errors as suggested in the Python examples, but every attempt fails with the same error.

Here’s my current implementation:

$ytService = new Google_YoutubeService($client);
if ($client->getAccessToken()) {
    echo "Authentication successful";
    
    $videoSnippet = new Google_VideoSnippet();
    $videoSnippet->setTitle = "Test Upload Video";
    $videoSnippet->setDescription = "Sample video upload description";
    $videoSnippet->setTags = array("demo","test");
    $videoSnippet->setCategoryId(22);

    $videoStatus = new Google_VideoStatus();
    $videoStatus->privacyStatus = "private";

    $videoObj = new Google_Video();
    $videoObj->setSnippet($videoSnippet);
    $videoObj->setStatus($videoStatus);

    $fileContent = file_get_contents("sample.mp4");
    $uploadMedia = new Google_MediaFileUpload("video/mp4", $fileContent);
    
    $hasError = true;
    $attempts = 0;
    $serverErrors = array(500, 502, 503, 504);
    
    while($attempts < 10 && $hasError) {
        try{
            $response = $ytService->videos->insert("status,snippet", 
                                                 $videoObj, 
                                                 array("data" => $fileContent));
            $hasError = false;
        } catch(Google_ServiceException $ex) {
            echo "Service Exception: ".$ex->getCode()
                 . " Error: ".$ex->getMessage();
            if(!in_array($ex->getCode(), $serverErrors)){
                break;
            }
            $attempts++;
        }
    }
    
    $_SESSION['token'] = $client->getAccessToken();
} else {
    $authenticationUrl = $client->createAuthUrl();
    echo "<a href='$authenticationUrl'>Authorize Access</a>";
}

Am I missing something in my approach or is there an issue with how I’m handling the file upload process?

you’re not using the media upload right - pass the Google_MediaFileUpload object to the insert method instead of raw file content in the data parameter. remove the data array and use $uploadMedia as the third parameter.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.