joi, 9 noiembrie 2023

Upload video to YouTube using PHP

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// youtube config
DEFINE('CHUNK_SIZE_BYTES', 1 * 1024 * 1024);
DEFINE('OAUTH_CLIENT_ID', '<replace_me>');
DEFINE('OAUTH_CLIENT_SECRET', '<replace_me>');
DEFINE('DEVELOPER_KEY', '<replace_me>');
DEFINE('REFRESH_TOKEN', '<replace_me>');

DEFINE('VIDEO_DIR', '/replace/with/real/path/');

require_once "youtube/Google_Client.php";
require_once 'youtube/contrib/Google_YouTubeService.php';

try {
   
    $client = new Google_Client();
    $client->setClientId(OAUTH_CLIENT_ID);
    $client->setClientSecret(OAUTH_CLIENT_SECRET);
    $client->setDeveloperKey(DEVELOPER_KEY);
    $client->refreshToken(REFRESH_TOKEN);
    $token = $client->getAccessToken();
    echo "Connected to youtube account!";
   
} catch (Google_Exception $e) {
   
    echo $e->getMessage();
    die();
   
}

$video_title        = "Video title replace me";
$video_description  = "Video description replace me";
$video_description  .= "\nVidea description new line replace me";
$video_tags         = array("replace", "me", "tags");
$video_category     = "19";

$youtube = new Google_YouTubeService($client);
echo "Created youtube service...";

$snippet = new Google_VideoSnippet();
$snippet->setTitle($video_title); // 100 chars max
$snippet->setDescription(htmlspecialchars($video_description));
$snippet->setTags($video_tags);
$snippet->setCategoryId($video_category);

$status                = new Google_VideoStatus();
$status->privacyStatus = "unlisted";

$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);

echo "Create video with status and snippet";

$video_name    = "replace_with_video_name.avi" // extensions may be whatever, mpeg, mp4, avi, flv...

$err           = null;
$error_message = null;
$video_path    = VIDEO_DIR . $video_name;
$video_path    = realpath($video_path);
echo "File:" . realpath($video_path);

try {
    // Create a MediaFileUpload with resumable uploads
    $media = new Google_MediaFileUpload('video/*', null, true, CHUNK_SIZE_BYTES);
    echo "Created media upload";
    echo "Chunk size: " . CHUNK_SIZE_BYTES;

    if(file_exists($video_path));
        echo "File exists!";          

    if (is_readable($video_path))
        echo "File is readable!";
    else
        echo "File is NOT readable!";

    echo "Size: " . filesize($video_path);

    $media->setFileSize(filesize($video_path));

    echo "Start media upload";          

    // Create a video insert request
    $insertResponse = $youtube->videos->insert("status,snippet", $video, array(
        'mediaUpload'                   => $media,
    ));

    $uploadStatus = false;

    // Read file and upload chunk by chunk
    $handle = fopen($video_path, "rb");
    $counter = 0;
    while (!$uploadStatus && !feof($handle)) {
        $counter++;
       
        $chunk = fread($handle, CHUNK_SIZE_BYTES);
        $uploadStatus = $media->nextChunk($insertResponse, $chunk);
       
        if($uploadStatus)
            echo "Uploaded " . $counter;
        else
            echo "Still uploading... " . $counter;
    }

    fclose($handle);
   
    // youtube video id
    $youtube_id = $uploadStatus['id'];
   
    echo "Video url: https://www.youtube.com/watch?v=" . $youtube_id;
   
    if($uploadStatus)
        echo "Uploading complete!";
    else
        echo "Uploading failed!";
       
catch(Google_ServiceException $e){
    $err = true;
    $error_message  = "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br/>";
    $error_message .= "Stack trace is ".$e->getTraceAsString();
}
catch(Google_Exception $e){
    $err = true;
    $error_message  = "Caught Google Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br/>";
    $error_message .= "Stack trace is ".$e->getTraceAsString();        
}
catch(Google_IOException $e){
    $err = true;
    $error_message  = "Caught Google Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br/>";
    $error_message .= "Stack trace is ".$e->getTraceAsString();        
}

echo "Finished!";      

if ($err) {
    echo $error_message;
    echo "Uploading failed!";
}
else{
    echo "no errors!";
}      

Niciun comentariu:

Trimiteți un comentariu