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.
Related
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.
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
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
Hi Im trying Google drive integration v3 in php to upload file from my web page i do not want to use picker. I have successfully done oauth and login. I can create a file in the drive but with empty data. the error i get is permission to write i have given public access to that folder. How can i solve this and write the content to that file.
My code after auth(successfull) redirect.
first.php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('conf/client_id.json');
//$scope='https://www.googleapis.com/auth/drive.file';
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope(Google_Service_Drive::DRIVE_FILE);
$client->addScope(Google_Service_Drive::DRIVE);
$client->addScope(Google_Service_Drive::DRIVE_APPDATA);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
$data = file_get_contents("a.png");
// create and upload a new Google Drive file, including the data
$file = new Google_Service_Drive_DriveFile($client);
$file->setName('img_'.uniqid().'.png');
$file->setMimeType('image/png');
//$parent = new Google_ParentReference();
//$parent->setId("0B687nRLFFN08ZXg0WU9Zb3VQaEE");
//$file->setParents(array($parent));
//$file->setParents(array('setId'=>"0B687nRLFFN08ZXg0WU9Zb3VQaEE"));
$createdFile = $service->files->create($file, array(
'data' => file_get_contents("a.png"), //$data
'mimeType' => 'image/png',
'uploadType' => 'media'
));
}
else {
$redirect_uri='http://'.$_SERVER['HTTP_HOST'].'/google/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
I'm using PHP to put some runtime created files on a specific Google Drive account.
If I'm logged on google with an account and I launch my script, these files will be uploaded on this account, even I use client ID and secret of a different account
Use case:
I'm logged with a#gmail.com, I use my script and files are sent to a#gmail.com's Google Drive instead of b#gmail.com's Google Drive
How can I upload these files to b#gmail.com account even if I'm logged with a#gmail.com account?
Thanks
The ex. code
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId(/*client id*/);
$drive->setClientSecret(/*client secret*/);
$drive->setRedirectUri(/*redirect uri (the same URI in the API configuration)*/);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$createdFile = $service->files->insert($file, array(
'data' => 'example',
'mimeType' => 'text/plain',
));
return true;
EDIT:
I use pathfinder solution and create a service account.
It seems working but I've still a problem: at the end of execution I can't find my file on gDrive...maybe I've done an invomplete configuration, even if I read the doc...
This is the code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<email_in_api_access>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'google-api-phpclient/<api_key_file>-privatekey.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array($DRIVE_SCOPE),
$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
$gdrive = new Google_DriveService($client);
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$createdFile = $gdrive->files->insert($file, array(
'data' => 'A test document',
'mimeType' => 'text/plain',
));
return true;