I've been trying to get the Google Drive PHP API set up to upload a simple file to a shared drive using the following code.
<?php
require_once '../../../php/Services/JSON.php';
require '../vendor/autoload.php';
require '../helper.php';
$chunkSizeBytes = 1048576;
$client = new Google_Client();
$client->setAuthConfig(__DIR__.'/SERVICE-ACCOUNT-CREDENTIALS.json');
$client->setApplicationName('Uploader');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setDefer(true);
$file = 'testUpload.txt';
$service = new Google_Service_Drive($client);
$params = [
'fields' => 'id',
'supportsAllDrives' => true
];
$req = $service->files->create(new Google_Service_Drive_DriveFile([
'name' => $file,
'teamDriveId' => 'DRIVE ID',
'parents' => '1Ik-tFv8UaOmlnZ3ojgPPba0o3hauh_63',
'mimeType' => Helper::get_mime_type($file)
]), $params);
$media = new Google_Http_MediaFileUpload($client, $req, Helper::get_mime_type($file), null, true, $chunkSizeBytes);
$media->setFileSize(filesize($file));
$status = false;
$fileHandler = fopen($file, 'rb');
while(!$status and !feof($fileHandler)) {
$chunk = fread($fileHandler, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($fileHandler);
$client->setDefer(false);
echo "https://drive.google.com/open?id=".$status['id']."\n";
After running this code it gives me a link to a file, but when I visit the link it says I need permission to access the file. When I open the folder on the shared drive the file is nowhere to be seen, so it's being uploaded, but not to the correct place as far as I know. I want to make sure that this file is uploaded to the shared drive, and to the folder specified, but so far I haven't been able to do so. I know some parameters have been deprecated from the API, but I'm pretty sure all the parameters that I'm using are not deprecated. I'm unsure of what I'm doing wrong, so any additional guidance would be appreciated, thanks!
The servier account is not you. The service account is uploading the file there for it owns the file. If you want access to it have the service account grant you access to it though permissions.create
$optParams = array(
'emailMessage' => '[YourValue]',
'sendNotificationEmail' => '[YourValue]',
'supportsTeamDrives' => '[YourValue]',
'transferOwnership' => '[YourValue]',
'fields' => '*'
);
return $service->permissions->CreatePermissions($fileId, $optParams);
Also remember to add supportsAllDrives parameter to the initial file upload.
Related
I am working on a project in which I need to upload a .xlsx file to my google drive via Google Drive API. Then also to get back the link so I can store it into MySQL Database.
The Uploading part is done. The problem is, how can I get back the file link so I can edit it using Google Sheets. I think I need to add Custom File ID To my file. I really don't know where to add it. My code is below:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
$filefullname=$_GET['accid'].' '.$_GET['name'].'.xlsx';
// UPLOADING OF FILE TO GOOGLE DRIVE////////////////////////////////////
//fopen('./client_sheets/'.$_GET['name'], "w");
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_Service_Drive_DriveFile();
$file_path = './client_sheets/'.$filefullname;
$mime_type = finfo_file($finfo, $file_path);
$file->setName($filefullname);
$file->setDescription('This file contains details about: '.$filefullname.' || Client of GT Security');
$file->setMimeType($mime_type);
$file->setName($filefullname);
$createdFile = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type,
'fields' => 'id'
)
);
print 'File ID: %s' % $createdFile->getId();
More info: I used PhpSpreadsheet to create the .xlsx file. Please can somebody add the FileID Field for me? Also, can somebody explain to me how to get the file link so I can edit it using Google Sheets?
In this case you can use the Google Drive automatic conversion feature. When you create the file in google drive it will be automatically converted to a spreadsheet file. So that you can open it via the spreadsheet service and get the url you need to store in your db.
Create and convert the .xlsx to a spreadsheet file:
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $filefullname,
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents($file_path);
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
Get the spreadsheet url:
$spreadsheetId = $file->id;
$sheetService = new Google_Service_Sheets($client);
$response = $service->spreadsheets->get($spreadsheetId);
$sheetUrl = $response->getSpreadsheetUrl();
References:
PHP Spreadsheet class methods
Import to Google Docs types
Hi am using this OneDrive SDK . https://github.com/krizalys/onedrive-php-sdk . I am using PHP. What I need is to create a cronjob that will fetch my files in OneDrive and save it to my local directory. It works fine following the tutorial in the SDK. However, the way that SDK works is it needs you to be redirected to Microsoft account login page to be authenticated.
This will require a browser. My question, is it possible to do this by just running it in the backend like a cron? I can't seem to find a way to do it using the SDK. In Google, they will provide you a key to access the services without logging in every time. I am not sure about OneDrive.
$localPath = __DIR__.'/uploads/';
$today = date('Y-m-d');
$folder = $client->getMyDrive()->getDriveItemByPath('/'.$today);
echo "<pre>";
try {
$files = $folder->getChildren();
$createdDirectory = $localPath.$today;
// Check if directory exist
if(is_dir($createdDirectory)){
echo "\n"." Directory ".$createdDirectory." already exists, creating a new one..";
// Create new directory
$uuid1 = Uuid::uuid1();
$createdDirectory = $createdDirectory.$uuid1->toString();
echo "\n".$createdDirectory." created..";
}
// Create directory
mkdir($createdDirectory);
echo "\n".count($files)." found for ".$today;
// Loop thru files inside the folder
foreach ($files as $file){
$save = $file->download();
// Write file to directory
$fp = fopen($createdDirectory.'/'.$file->name, 'w');
fwrite($fp, $save);
echo("\n File ".$file->name." saved!");
}
} catch (Exception $e){
die("\n".$e->getMessage());
}
die("\n Process Complete!");
My code is something like that in the redirect.php
It doesn't look like that SDK supports the Client Credentials OAuth Grant. Without that, the answer is no. You may want to look at the official Microsoft Graph SDK for PHP which supports this via the Guzzle HTTP client:
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
$accessToken = $token->access_token;
I have been trying to upload files to my google drive account via service-account using php. I guess the file is successfully uploaded as I can print the file id, file created time and all other information.
Here is my issue: When I login into my google drive account, I cannot see any uploaded file. Where is the file hiding or what should I do?
Here is the code:
require __DIR__ . '/vendor/autoload.php'; //api
$serviceAccount = "xxx#xxxxxx.iam.gserviceaccount.com";
$key_file = "mykey-goes-here.p12";
$auth = new Google_Auth_AssertionCredentials(
$serviceAccount,
array('https://www.googleapis.com/auth/drive.file'),
file_get_contents($key_file)
);
$client = new Google_Client();
$client->setAssertionCredentials( $auth );
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("my file name");
$file->setDescription('testing desc');
$file->setMimeType('text/plain');
// Provide file name here and path in below
$result = $service->files->insert($file, array(
'data' => file_get_contents("test.txt"),
//'mimeType' => 'text/plain',
'mimeType' => 'application/octet-stream',
'uploadType' => 'media',
//'uploadType' => 'multipart'
));
// Uncomment the following line to print the File ID
printf("File ID: %s\n", $result->id);
echo "<br><br>";
echo '<pre>'; print_r($result); echo'</pre>';
solution:
I discovered that Files uploaded by service account is not available via UI.
To solve the issue, one need to delegate/authorize the application to use the said service account.
link
There is no error. Why is not the file sent?
error_reporting(E_ALL);
ini_set('display_errors',1);
try{
require_once './vendor/autoload.php';
$client = new Google_Client();
$oauth_credentials = './vendor/test.json';
$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setScopes('https://www.googleapis.com/auth/drive');
$driveService = new Google_Service_Drive($client);
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'photo.png'));
$content = file_get_contents('./vendor/plik.png');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'image/png',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
}catch(Exception $e){
echo $e->getMessage();
}
You appear to be using a service account. A service account is not you. Files uploaded using a service account will be uploaded to the service accounts google drive account.
Tips for using service accounts with google drive:
No there is no web view for the service accounts files.
Do a file.list to see if the file was in fact uploaded to your service account.
share a directory on your personal google drive account and have the service account upload to that. Remember to grant yourself permissions to the file.
I am uploading files to my google drive account. This are the codes:
putenv('GOOGLE_APPLICATION_CREDENTIALS=xxxx.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Drive::DRIVE);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
$tempfile = "birds-image-11.jpg";
$file = new Google_Service_Drive_DriveFile(array(
'name' => 'tc-test.jpg',
));
$service = new Google_Service_Drive($client);
$result = $service->files->create($file, array(
'data' => file_get_contents($tempfile),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media',
'fields' => 'id, name,kind'
));
printf("File ID: %s\n", $result->id);echo '<br>';
printf("File Name: %s\n", $result->name);echo '<br>';
printf("File Kind: %s\n", $result->kind); echo '<br>';
I can see the id, name and kind returned. So that's mean the files has been uploaded right? But When I goto my google drive, I can't see the files.
If I list the files from the api $service->files->listFiles(); I can see the uploaded file object returned.
Why I can't see it in my drive (https://drive.google.com/drive/my-drive) and where should I looked for the file?
By the way, I am using service account for the api.
You will also need to set the file's parent folder(s), which can be the user's "My Drive" or any other folder(s).
Specify folder name while upload file via Google Drive API
https://developers.google.com/drive/v3/reference/files/update