Get files from a specific Google Drive Folder - php

I am working on downloading a particular file shared with me in Google Drive. I developed the script to get the list of files and folders in my account. In that folders, I need to get the files list. While trying to do this I am getting the below error,
Notice: Undefined property: Google_Service_Drive::$children
My Code:
$client = new Google_Client();
$client->setApplicationName('Google Drive API');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$service = new Google_Service_Drive($client);
$optParams = array(
"pageSize" => 10,
"fields" => "nextPageToken, files(id, name)",
"q" => "sharedWithMe and name contains 'Folder Name'"
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $files) {
printf("%s (%s)\n", $files->getName(), $files->getId());
$folderId = $files->getId();
$parameters = array();
$children = $service->children->listChildren($folderId, $parameters);
}
}
I need the fileId in the folder, so I can download it.
Let me know if I am missing any scope or anything wrong on my code.
Your suggestions will be very helpful.
Thanks in advance.

Related

copy file with google drive api v3 return "The provided file ID is not usable."

There a error when i try to copy file use google drive api. Is there a param that i lack?
this the error i get :
{
"error":{
"errors":[
{
"domain":"global",
"reason":"fileIdNotUsable",
"message":"The provided file ID is not usable.",
"locationType":"other",
"location":"file.id"
}
],
"code":400,
"message":"The provided file ID is not usable."
}
}
This my code :
$client = new \Google_Client();
$client->setClientId(env('GOOGLE_DRIVE_CLIENT_ID'));
$client->setClientSecret(env('GOOGLE_DRIVE_CLIENT_SECRET'));
$client->refreshToken(env('GOOGLE_DRIVE_REFRESH_TOKEN'));
$service = new \Google_Service_Drive($client);
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);
$files = $service->files->listFiles($optParams);
foreach($files as $value){
if($value->mimeType != 'application/vnd.google-apps.folder'){
$service->files->copy($value->id, $value);
}
}

How can I get download url from a file of google drive with php?

I´ve followed this guide:
https://developers.google.com/drive/api/v3/quickstart/php?authuser=1
Now I want to get the dowload link from a file. I am trying to use $file->getDownloadUrl(), but I get the following error:
Fatal error: Uncaught Error: Call to undefined method Google_Service_Drive_DriveFile::getDownloadUrl() in C:\xampp\htdocs\Prueba\quickstart.php:84
Stack trace:
#0 {main}
thrown in C:\xampp\htdocs\Prueba\quickstart.php on line 84
This is my code:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 10 files.
$optParams = array(
'pageSize' => 1,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n", $file->getName(), $file->getId());
print($file->getDownloadUrl());
}
}
By the way, client has authorization to download files, because I have defined like this:
$client->setScopes(Google_Service_Drive::DRIVE_READONLY);
EDIT:
Finally, I have been able to download PDF files with the following code:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 3 files.
$optParams = array(
'pageSize' => 3,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n", $file->getName(), $file->getId());
$fileId = $file->getId();
$fileToDown = $service->files->get($fileId, array('alt' => 'media'));
file_put_contents($file->getName(),$fileToDown->getBody());
}
}
The method getDownloadUrl() not exist. Try:
$file->downloadUrl;
You are using a method that does not exist.
Check here for an overview of the methods available. You want to use the getWebContentLink() method.
In line with the announcement webContentLink is now the way to get links that download files from Drive.

How to see files uploaded to google drive via 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

How to set scopes for accesing list of excelsheets of google drive in php

I want to list the excel files from google drive. For this I am using the DRIVE API Quickstart Guid. But having errors. Mentioned below:
**define('SCOPES', implode(' ', array(
Google_Service_Sheets::SPREADSHEETS_READONLY)
));
//Scopes authorized client object
$client = getClient();
// code to print the names and id up to 10 files.
$service = new Google_Service_Sheets($client);
//$finfo = finfo_open(FILEINFO_MIME_TYPE);
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)');
//$file = new Google_Service_Sheets($client);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n", $file->getName(), $file->getId());
}
}**
Notice: Undefined property: Google_Service_Sheets::$files in C:\xampp\htdocs\today\quickstart.php on line 82
Fatal error: Uncaught Error: Call to a member function listFiles() on null in C:\xampp\htdocs\today\quickstart.php:82 Stack trace: #0 {main} thrown in C:\xampp\htdocs\today\quickstart.php on line 82
Try reading this document - Retrieve a list of spreadsheets
The Google Sheets API supports fetching a list of spreadsheets for the authenticated user. Note however that you cannot create or delete spreadsheets via this API.
You can request a feed containing a list of the currently authenticated user's spreadsheets by sending an authenticated GET request to the following URL:
https://spreadsheets.google.com/feeds/spreadsheets/private/full
OR
Use Search for Files (Drive API)
mimeType string contains, =, != MIME type of the file.
Search for folders using the folder-specific MIME type
mimeType = 'application/vnd.google-apps.folder'
Here is a sample code:
$pageToken = null;
do {
$response = $driveService->files->listFiles(array(
'q' => "mimeType='image/jpeg'",
'spaces' => 'drive',
'pageToken' => $pageToken,
'fields' => 'nextPageToken, items(id, title)',
));
foreach ($response->items as $file) {
printf("Found file: %s (%s)\n", $file->name, $file->id);
}
} while ($pageToken != null);
Note: you've link a Sheets API quickstart and not Drive API quickstart, here is the link for the quickstart for Drive API.
Hope this helps.

Google Drive API - Downloading a file

Using a oauth2 connection I have a working script (listing documents from Google Drive), I only need to add a download/export function.
Note: access_token / refresh_token are already set (different script)
//error_reporting(E_ALL);
require_once('vendor/autoload.php');
require_once('vendor/google/apiclient/src/Google/Client.php');
require_once('vendor/google/apiclient-services/src/Google/Service/Drive.php');
session_start();
$client_id = '<client_id>';
$client_secret = '<client_secret>';
$redirect_uri = '<redirect_uri>';
$client = new Google_Client();
$client->setApplicationName("Google Calendar");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->addScope("https://www.googleapis.com/auth/drive");
## Step 1: Set token ##
$array = array(
'access_token' => 'xxxxxxxxxxxxx', //set access token
'token_type' => 'Bearer',
'expires_in' => 0,
'created' => 0,
'refresh_token' => 'xxxxxxxxxxxxx', //set refresh token
);
$_SESSION['token'] = $array;
## Step 2: If token is active, list documents ##
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
// Get the API client and construct the service object.
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 10 files.
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n<br>", $file->getName(), $file->getId());
}
}
}
Unfortunately I'm unable to create a direct download link (for non public files). I have found the following documentation but I'm lost on how I can apply this:
https://developers.google.com/drive/v3/reference/files/get
https://developers.google.com/drive/v3/web/manage-downloads
The PHP example from "manage-downloads" results in an error:
Undefined variable: driveService in ... my_drive_script.php
Simply adding a link works, but only for shared documents (or if I'm logged in under the same user).
$fileid = $file->getId();
printf("<a href='https://docs.google.com/document/d/$fileid/export?format=doc'>Download doc</a>");
I have used the link format from http://www.labnol.org/internet/direct-links-for-google-drive/28356/
It should be possible to download non public files, right?

Categories