Last active
August 1, 2023 08:30
-
-
Save azhar25git/1f388c439316224929e5a4f13246f794 to your computer and use it in GitHub Desktop.
Upload to your Google Drive via PHP Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// error_reporting( E_ALL ); | |
// you need to get Google OAuth Client Package with this command: composer require google/apiclient:"^2.0" | |
require __DIR__ . '/vendor/autoload.php'; | |
// Credentials for your Drive App created on https://console.cloud.google.com | |
$clientId = 'xxxxxxapps.googleusercontent.com'; | |
$clientSec = 'xxxxxxxx'; | |
// Get access tokens from https://developers.google.com/oauthplayground using your Own Client ID and Cilent Secret | |
// The Scope must be from Drive API example: https://www.googleapis.com/auth/drive, https://www.googleapis.com/auth/drive.file | |
$accessToken = 'xxxxxxx'; | |
$refreshToken = 'xxxxxxxxx'; | |
// general redirect URL | |
$redirectUrl = 'urn:ietf:wg:oauth:2.0:oob'; | |
// generate a token object from tokens your scope should be mentioned here | |
$tokenObj = '{"access_token":"'.$accessToken.'","expires_in":3600,"scope":"https:\/\/www.googleapis.com\/auth\/drive.file","token_type":"Bearer","created":1555475349,"refresh_token":"'.$refreshToken.'"}'; | |
// you can also provide a token.json file downloaded from console.cloud.google.com | |
$tokenPath = 'token.json'; | |
// file to upload | |
$file_path = realpath('files/cat.zip'); | |
$file_name = basename($file_path); | |
// Get the API client and construct the service object. | |
$client = getClient($clientId, $clientSec, $redirectUrl, $tokenObj, $tokenPath); | |
$service = new Google_Service_Drive($client); | |
if ($service){ | |
$mime_type = finfo_file( finfo_open(FILEINFO_MIME_TYPE) , $file_path ); | |
$fileMetadata = new Google_Service_Drive_DriveFile(array( | |
'name' => $file_name, 'mimeType' => $mime_type)); | |
$content = file_get_contents($file_path); | |
// file upload process | |
try { | |
$file = $service->files->create($fileMetadata, array( | |
'data' => $content, | |
'mimeType' => $mime_type, | |
'uploadType' => 'multipart', | |
'fields' => 'id')); | |
printf("Upload Success. File ID: %s\n", $file->id); | |
} | |
catch (\Exception $e) { | |
echo $e->getMessage();exit; | |
} | |
} | |
/** | |
* Returns an authorized API client. | |
* @return Google_Client the authorized client object | |
*/ | |
function getClient($clientId, $clientSec, $redirectUrl, $tokenObj = '', $tokenPath = '') | |
{ | |
$client = new Google_Client(); | |
$client->setApplicationName('RTG Google Drive API Quickstart'); | |
$client->setScopes(Google_Service_Drive::DRIVE_FILE); | |
$client->setClientId($clientId); | |
$client->setClientSecret($clientSec); | |
$client->setRedirectUri($redirectUrl); | |
$client->setAccessType('offline'); | |
$client->setApprovalPrompt('auto'); | |
// Load previously authorized token from a file, if it exists. | |
// The file token.json stores the user's access and refresh tokens, and is | |
// created automatically when the authorization flow completes for the first | |
// time. | |
if (file_exists($tokenPath) && is_file($tokenPath)) { | |
$accessTokenArray = json_decode(file_get_contents($tokenPath), true); | |
if ($accessTokenArray != null) { | |
$client->setAccessToken($accessTokenArray); | |
$accessToken = $accessTokenArray; | |
} | |
} | |
// if file not found then token should be taken from Token Object | |
else if (is_string($tokenObj) && $tokenObj !=null && $tokenObj != '') { | |
$accessTokenArray = json_decode($tokenObj , true); | |
$client->setAccessToken($accessTokenArray); | |
// $accessToken = $accessTokenArray['access_token']; | |
} | |
// If there is no previous token or it's expired. | |
if ($client->isAccessTokenExpired()) { | |
// Refresh the token if possible, else fetch a new one. | |
if ($client->getRefreshToken()) { | |
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); | |
} | |
// custom access token creation if there is no token file or no token object provided | |
else { | |
// Request authorization from the user. | |
$authUrl = $client->createAuthUrl(); | |
echo ' | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<a href='.$authUrl.' id="link" target="_blank">Click to Generate Token</a> | |
<script> | |
// document.getElementById("link").click(); | |
</script> | |
</body> | |
</html> | |
'; | |
print '<form action="index.php" method="GET"> | |
<input type="text" name="verify" placeholder="Enter verification code:"> | |
<input type="submit" name="Submit" value="Submit"> | |
</form>'; | |
if(isset($_GET['verify']) && $_GET['verify'] != '') { | |
$authCode = $_GET['verify']; | |
// Exchange authorization code for an access token. | |
if(isset($authCode)) { | |
// $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); | |
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode); | |
$client->setAccessToken($accessToken); | |
} | |
// Check to see if there was an error. | |
if (array_key_exists('error', $accessToken)) { | |
throw new Exception(join(', ', $accessToken)); | |
} | |
} | |
} | |
// Uncomment this to Save the token to a file. | |
// if (!file_exists(dirname($tokenPath))) { | |
// mkdir(dirname($tokenPath), 0700, true); | |
// } | |
// file_put_contents($tokenPath, json_encode($client->getAccessToken())); | |
} | |
return $client; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment