I have a code it and it is working problem is its only working for 1 person. So if I logged in then it will not show login screen ever again for any user unless that token expires.
index.php
<?php
session_start();
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('client_id.json');
$client->addScope(Google_Service_Drive::DRIVE);
if (file_exists("credentials.json")) {
$access_token = (file_get_contents("credentials.json"));
$client->setAccessToken($access_token);
//Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
$drive_service = new Google_Service_Drive($client);
$files_list = $drive_service->files->listFiles(array())->getFiles();
if (count($files_list) == 0) {
print "No files found.\n";
} else {
foreach ($files_list as $file) {
$res['name'] = $file->getName();
$res['id'] = $file->getId();
$files[] = $res;
}
print_r($files);
}
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
So index file checks if credentials.json files has access token or not if exists then list files other wise login user through callback file.
callback.php
<?php
session_start();
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_id.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/callback.php');
$client->addScope(Google_Service_Drive::DRIVE); //::DRIVE_METADATA_READONLY
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
file_put_contents("credentials.json", json_encode($access_token));
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
This is the wrong approach I guess because it only stores 1 token and shows its value. Is there way that every person who is not logged in needs to login to see his files list.
Thanks.