How to see files uploaded to google drive via PHP? - php

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

Related

Permissions issues with uploading to team drive

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.

How To Set Custom File ID While Uploading a File To Google Drive Using Google Drive API? (PHP)

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

PHP gdrive upload file

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.

Can't find my files in google drive that uploaded via Google Drive API

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

google drive integration v3 in php

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));
}

Categories