What is OAuth 2.0 and how is it used in PHP for authentication with Google APIs?

OAuth 2.0 is an authorization framework that allows a user to grant a third-party application limited access to their resources without sharing their credentials. In PHP, OAuth 2.0 can be used for authentication with Google APIs by obtaining an access token from Google's OAuth 2.0 server and including it in API requests.

<?php

// Include Google API client library
require_once 'vendor/autoload.php';

// Set up OAuth 2.0 client
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

// Redirect to Google's OAuth 2.0 server for authorization
if (!isset($_GET['code'])) {
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    // Exchange authorization code for access token
    $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $access_token = $client->getAccessToken();
    
    // Use access token to make API requests
    $drive = new Google_Service_Drive($client);
    $files = $drive->files->listFiles();
    
    // Output list of files
    foreach ($files->getFiles() as $file) {
        echo $file->getName() . "<br>";
    }
}
?>