Drive API Not Syncing PHP - php

I am using the Google Drive API in my web application. I completely removed the "Getting Started" file and added a couple folders about 5 days ago to the service accounts Google Drive that I am connecting to. But instead of the API returning current data (two folders), it returns old data (the "Getting Started.pdf" file).
Why is the API doing this? How can I use PHP to fix it? I prefer using the SDK functions over the URLs, just so you know.
The code that isn't working is
$pageToken = null;
do {
$response2 = $service->files->listFiles(array(
//'q' => "mimeType='application/vnd.google-apps.folder'",
'spaces' => 'drive',
'pageToken' => $pageToken,
'fields' => 'nextPageToken, files(id, name)',
));
foreach ($response2->files as $file2) {
echo "Found file: " . $file2->name . " " . $file2->id;
}
} while ($pageToken != null);

Related

Microsoft OneDrive SDK run as cron

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;

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

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.

PHP Script not proceeding ahead with Amazon S3 Upload

I am trying to upload a file to the Amazon S3 using the AWS PHP SDK but whenever I try uploading, the script gives output till the PutObject operation but no output after that operation. I am not even able to dump the result object. The credentials are stored in the .aws in the root folder of my test machine (running Ubuntu). Below is the code -
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
echo "<br />".realpath(UPLOAD_DIR . $apiKEY . "/" . $name);
try {
$result = $s3->putObject([
'Bucket' => 'quicklyusercannedspeechbucket',
'ContentType' => 'text/plain',
'Key' => $apiKEY . "/" . $name,
'SourceFile' => realpath(UPLOAD_DIR . $apiKEY . "/" . $name)
]);
var_dump($result);
}
catch(\Aws\S3\Exception\S3Exception $e) {
echo $e->getAwsErrorCode();
}
echo "Finished";
var_dump($result);
When I run the above code, I don't get any output for the $result array. Any idea what might be happening?
Any help is appreciated ^_^
-Pranav
Use below code to view if your image is uploaded successfully
try {
$result = $s3->putObject([
'Bucket' => 'quicklyusercannedspeechbucket',
'ContentType' => 'text/plain',
'Key' => $apiKEY . "/" . $name,
'SourceFile' => realpath(UPLOAD_DIR . $apiKEY . "/" . $name)
]);
$s3file='http://quicklyusercannedspeechbucket.s3.amazonaws.com/'.$name;
echo "<img src='$s3file'/>";
echo 'S3 File URL:'.$s3file;
var_dump($result);
}
catch(\Aws\S3\Exception\S3Exception $e) {
echo $e->getAwsErrorCode();
}
You can get step by step detail from here Amazon S3 File Upload Using PHP
It seems that I had put the credentials in the wrong folder. As per the NGINX, the default folder for storing the credentials was /var/www rather than the home directory of the user.
Also, I turned on the display_errors in the php.ini which helped me find that the AWS SDK was having problems with the credentials.
Thanks!

aws s3 php sdk 2 SignatureDoesNotMatch Error

I have a bucket created in ap-southeast-1 region with ACL set to private-read. I am able to successfully upload files to folders inside the bucket using the AWS PHP SDK 2 S3Client class. However, I also need to display a link to these files in my application. Hence, when a user clicks a button, I send an AJAX request to my server file, and I get the signedURL which is returned back to the user via json string. However, the url always returns with an XML with error SignatureDoesNotMatch.
Code for getting the signedURL below:
//create the AWS reference string
$client = S3Client::factory(
array(
'key' => T_AWS_KEY,
'secret' => T_AWS_SECRET,
'region' => T_BASE_REGION
)
);
//method 1 - using Command Object
$command = $client->getCommand('GetObject', array(
'Bucket' => T_BASE_BUCKET . "/" . $firmId . "/invoices" ,
'Key' => $arr['file_reference_url'] ,
'ResponseContentDisposition' => 'attachment;filename=' . arr['file_reference_url']
));
$signedUrl = $command->createPresignedUrl('+10 minutes');
echo $signedUrl . "\n\n";
//method 2 - using getObjectUrl
echo $client->getObjectUrl(T_BASE_BUCKET . "/" . $firmId . "/invoices", $arr['file_reference_url'], "+10 minutes");
Any help is appreciated.
It seems you may be confused about what buckets are. Buckets are not nested. It's likely that the value of T_BASE_BUCKET is your bucket and the other parts are part of the object key. Give this a shot:
$objectKey = $firmId . '/invoices/' . $arr['file_reference_url'];
echo $client->getObjectUrl(T_BASE_BUCKET, $objectKey, '+10 minutes');

Categories