<?php
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$youtube = new Google_Service_Youtube($client);
if (isset($_GET['code'])){
if (strval($_SESSION['state']) !== strval($_GET['state'])){
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location:' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()){
try{
$videoId = "VIDEO_ID";
$imagePath = "/path/to/file.png";
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$setRequest = $youtube->thumbnails->set($videoId);
$media = new Google_Http_MediaFileUpload(
$client,
$setRequest,
'image/png',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($imagePath));
$status = false;
$handle = fopen($imagePath, "rb");
while (!$status && !feof($handle)){
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
$client->setDefer(false);
$thumbnailUrl = $status['items'][0]['default']['url'];
$htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
$htmlBody .= sprintf('<li>%s (%s)</li>',
$videoId,
$thumbnailUrl);
$htmlBody .= sprintf('<img src="$s">', $thumbnailUrl);
$htmlBody .= '</ul>';
} catch(Google_Service_Exception Se){
$htmlBody .= sprintf('<p>A.service error occured: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e){
$htmlBody .=sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} ese{
$state = mt_rand();
$clilent->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Requred </h3>
<p>You need to <a href="$authUrl">authorize acceess</a>before proceeding.</p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Claim Uploaded </title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>