Skip to content

Instantly share code, notes, and snippets.

@hiddenpearls
Created September 2, 2015 04:28
Show Gist options
  • Save hiddenpearls/c4b8a78a40d0fc91e76c to your computer and use it in GitHub Desktop.
Save hiddenpearls/c4b8a78a40d0fc91e76c to your computer and use it in GitHub Desktop.
Fetch latest files from Google Drive using PHP
<?php
// Display erros if any on the page.
error_reporting(E_ALL);
ini_set("display_errors", 1);
session_start();
if(isset($_GET['action']) and $_GET['action'] == 'logout'){
unset($_SESSION['accessToken']);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Autoload Drive SDK
require 'lib/google-api-php-client/src/Google/autoload.php';
define('APPLICATION_NAME', 'Project Default Service Account');
define('CLIENT_SECRET_PATH', 'client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE_METADATA_READONLY)
));
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setRedirectUri('http://localhost/drive/upload-images.php');
$client->setAccessType('offline');
//formatPre($_SESSION['accessToken']);
if( !isset($_GET['code']) and !isset($_SESSION['accessToken'])) {
echo '<a target="_self" href="'. $client->createAuthUrl($client) . '">Click here to Authenticate</a>';
}
if( isset($_GET['code'])){
$accessToken = $client->authenticate($_GET['code']);
$client->setAccessToken($accessToken);
$_SESSION['accessToken'] = $accessToken;
}
if(isset($_SESSION['accessToken'])){
showLogOut();
if($client->isAccessTokenExpired()){
//$client->refreshToken($client->getRefreshToken());
$client->setAccessToken($_SESSION['accessToken']);
}
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 10 files.
$optParams = array(
'maxResults' => 10,
);
$results = $service->files->listFiles($optParams);
if (count($results->getItems()) == 0) {
echo "No files are stored in your Google Drive.\n";
} else {
echo "<br />Files:<br />";
foreach ($results->getItems() as $file) {
echo "File ID => " . $file->getId() . " , Title => " . $file->getTitle() . '<br /><br />';
}
}
}
function showLogOut(){
echo '<a target="_self" href="?action=logout">Logout</a>';
}
function formatPre($value){
echo '<pre>';
echo $value;
echo '</pre>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment