0
votes

I am trying to learn a simple web app (PHP) using Google drive API.

  1. Display list of files in the drive.
  2. Add a new file to the drive.

Code as follows:

<?php
session_start();

$url_array = explode('?', 'http://'.$_SERVER ['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$url = $url_array[0];

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$client = new Google_Client();
$client->setClientId(''); // Kept my id
$client->setClientSecret(''); //kept my key
$client->setRedirectUri($url);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

 if (isset($_GET['code'])) {
 $_SESSION['accessToken'] = $client->authenticate($_GET['code']);
 header('location:'.$url);exit;
 } elseif (!isset($_SESSION['accessToken'])) {
 $client->authenticate();
 } 

It works fine till here. The app gets authenticated and redirects back to my app. Now, I try displaying list of files.

Problem code:

 $service = new Google_DriveService($client);
 $result = array();
  $files = $service->files->listFiles();
  $result = array_merge($result, $files->getItems());
 print_r($result);

I get this error:

Error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/drive/v2/files: (401) Login Required' in C:\wamp\www\Sample\google-api-php-client\src\io\Google_REST.php

Can someone please help in correcting me and also I would be thankful in sharing simple code how to insert a doc.

1
Does a "logged in" state require setClientId and setClientSecret to be called, or does it require the execution of authenticate as well? Is the latter called (i.e. is your code query string populated and correct? - halfer

1 Answers

0
votes

Add this line after $client->authenticate();: $client->setAccessToken($accessToken);