oussama kamal
oussama kamal

Reputation: 1037

Delete file with google drive API PHP V3 permission error

I have an issue with google drive PHP API V3 I'm trying to remove a file from the drive using the code below:

This is the code I'm using:

<?php

require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Google Drive API PHP');
define('CREDENTIALS_PATH', '/root/.credentials/drive-php.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
    Google_Service_Drive::DRIVE_METADATA_READONLY
)
));

if (php_sapi_name() != 'cgi-fcgi') {
    throw new Exception('This application must be run on the command line.');
}

function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfig(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    $accessToken = json_decode(file_get_contents(CREDENTIALS_PATH), true);
    $client->setAccessToken($accessToken);
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents(CREDENTIALS_PATH, json_encode($client->getAccessToken()));
    }
    return $client;
}

$client = getClient();
$service = new Google_Service_Drive($client);

$optParams = array(
    'fields' => 'files(id, createdTime)'
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) != 0) {
    foreach ($results->getFiles() as $file) {
        $service->files->delete($file['id']);
    }
}

All is working I can get the ID of the file but when I try to delete it I get the below error. Any idea why please?

Thanks

PHP Fatal error:  Uncaught Google_Service_Exception: {
     "error": {
      "errors": [
       {
        "domain": "global",
        "reason": "insufficientPermissions",
        "message": "Insufficient Permission"
       }
      ],
      "code": 403,
      "message": "Insufficient Permission"
     }
    }

Upvotes: 0

Views: 3163

Answers (1)

Tanaike
Tanaike

Reputation: 201603

Google_Service_Drive::DRIVE_METADATA_READONLY cannot be used for deleting files using Drive API. So how about using Google_Service_Drive::DRIVE as the scope?

When you modified the scope, please remove the file of drive-php.json at /root/.credentials/, and run the script again. By this, the access token and refresh token reflected the modified scope can be retrieved.

And then, please confirm whether Drive API is enabled again.

If this was not useful for you, I'm sorry.

Upvotes: 1

Related Questions