Add this line after $client->authenticate();: $client->setAccessToken($accessToken);
List and upload to Google Drive API
-
28-06-2022 - |
Pregunta
I am trying to learn a simple web app (PHP) using Google drive API.
- Display list of files in the drive.
- 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.
Solución
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow