Search code examples
phpgoogle-drive-api

google drive api dont know where it saves the file but when fetched it shows the saved but not the others


I used the google drive api to insert a text file...

Build Service

function buildService() {

$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '[email protected]';

if($_SERVER['HTTP_HOST'] == 'localhost')
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'xxxxxxxx-privatekey.p12';
else
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = $_SERVER['DOCUMENT_ROOT'].'/xxxxx-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);
  return new Google_DriveService($client);
}

Retrieve Files

function retrieveAllFiles($service) {
  $result = array();
  $pageToken = NULL;

  do {
    try {
      $parameters = array();
      if ($pageToken) {
        $parameters['pageToken'] = $pageToken;
      }
      $files = $service->files->listFiles($parameters);

      $result = array_merge($result, $files->getItems());
      $pageToken = $files->getNextPageToken();
    } catch (Exception $e) {
      print "An error occurred: " . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);
  return $result;
}

Creating an instance and inserting

$service = buildService();

$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = "contents";

$createdFile = $service->files->insert($file, array('data' => $data,'mimeType' =>'text/plain',));

print_r($createdFile);

echo '<br>------<br>';

Retrieving files

$ret = retrieveAllFiles($service);

echo '<pre>';
print_r($ret);
  1. As in the fist call i insert a file...

  2. in the second call i am trying to list all files...

  3. when i try to list i could see only the inserted file but not the others which i could see in my drive by logging into docs.google.com. i am already having 6 files online

  4. as per the documentation i created service account with the private keys and the service account email.

so where will that file be store and how do i list all other files in the root of google drive?


Solution

  • You are inserting files in the application-owned account represented by the service account.

    If you want to manage (insert/list/...) files in another domain user's Drive account, you'll have to perform Domain-wide delegation: https://developers.google.com/drive/delegation