Google Drive API installation procedure using PHP Quickstart

Aug 24, 2020 PHP Beginner GoogleDrive

I used Google Drive API, so I have a memo

Set up connection using Quickstart

Install Google Client Library

composer require google/apiclient:^2.0

Download credentials

*If you have already set up the OAuth 2.0 client (If not set, set OAuth 2.0 client first)

Creating a sample program

PHP Quickstart | Google Drive API | Google Developers https://developers.google.com/drive/api/v3/quickstart/php

<?php
require __DIR__ .'/vendor/autoload.php';

if (php_sapi_name() !='cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Drive API PHP Quickstart'); //Specify the set application name
    $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
    $client->setAuthConfig('credentials.json'); //JSON path obtained here
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath ='token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

Executing the sample program

php quickstart.php
[hoge@hogehoge hoge]$ php quickstart.php
Open the following link in your browser:
https://accounts.google.com/o/oauth2/auth?response_type........
Enter verification code: