How do I read a Google Drive Spreadsheet in PHP?

How do I read a Google Drive Spreadsheet in PHP?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Unauthenticated Limit Trap in Google Drive API Calls

You are encountering a specific authentication barrier that trips up many developers: the "Daily Limit for Unauthenticated Use Exceeded" error. This message appears because your current implementation initializes a Google_Client but fails to complete the OAuth 2.0 flow to retrieve an access token. While you have correctly set up the client ID, secret, and redirect URIs in the Google API Console, the code snippet provided never calls $client->fetchAccessTokenWithAuthCode().

Without a valid access token, the Google Drive API treats your request as unauthenticated. Google allows a small number of these requests per day (typically 100), but once that quota is exhausted, it blocks further access with the exact error you are seeing. The fix requires implementing the full OAuth 2.0 authorization flow to exchange the user's credentials for a usable token.

Implementing the OAuth 2.0 Flow

To resolve this, you must redirect the browser to Google's consent screen after initializing the client. This step is non-negotiable for Drive API access unless you are using Service Accounts with specific scopes (which we will discuss later).

After setting up the $client object as shown in your example, you need to add a redirect URI that matches exactly what you configured in the Google API Console under "Authorized redirect URIs". If you set this to http://localhost, your code must handle that specific string.

Here is how you integrate the flow into your existing setup:

<?php
session_start();
require_once 'lib/gapi/Google_Client.php';
require_once 'lib/gapi/contrib/Google_DriveService.php';

// Configuration values from Google API Console
define('GDRIVE_CLIENT_ID', 'YOUR_CLIENT_ID'); 
define('GDRIVE_CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
define('GDRIVE_REDIRECT_URI', 'http://localhost'); // Must match console config exactly

$client = new Google_Client();
$client->setClientId(GDRIVE_CLIENT_ID);
$client->setClientSecret(GDRIVE_CLIENT_SECRET);
$client->setRedirectUri(GDRIVE_REDIRECT_URI);
$client->setScopes([
    'https://www.googleapis.com/auth/drive.file' // Use minimal required scopes
]);

// Generate the authorization URL
$authUrl = $client->createAuthUrl();

header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
exit;

This code outputs a URL that you must open in your browser. Upon visiting it, Google will ask you to grant permission to access your Drive. You will be redirected back to your GDRIVE_REDIRECT_URI with an authorization code appended to the query string (e.g., ?code=4/0A...).

You then need a second script or logic block to intercept that redirect and exchange the code for an access token:

<?php
session_start();
require_once 'lib/gapi/Google_Client.php';
require_once 'lib/gapi/contrib/Google_DriveService.php';

define('GDRIVE_CLIENT_ID', 'YOUR_CLIENT_ID'); 
define('GDRIVE_CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
define('GDRIVE_REDIRECT_URI', 'http://localhost');

$client = new Google_Client();
$client->setClientId(GDRIVE_CLIENT_ID);
$client->setClientSecret(GDRIVE_CLIENT_SECRET);
$client->setRedirectUri(GDRIVE_REDIRECT_URI);
$client->setScopes(['https://www.googleapis.com/auth/drive.file']);

// Check if we received an authorization code
if (isset($_GET['code'])) {
    $code = $_GET['code'];
    
    // Exchange the code for an access token
    $token = $client->fetchAccessTokenWithAuthCode($code);
    $client->setAccessToken($token);
    
    // Save the token to a file or database for persistence
    // This is crucial because tokens expire (usually after 1 hour)
    file_put_contents('credentials.json', json_encode($token));
    
    // Now you can use the client to interact with Drive
    $service = new Google_DriveService($client);
    $file = $service->files->get(GDRIVE_FILE_KEY);
    
    echo "Title: " . $file->getTitle();
} else {
    die("Authorization code not found.");
}
?>

Persisting Tokens and Avoiding the Daily Limit

The most common mistake after fixing the initial error is ignoring token expiration. The access token obtained via OAuth 2.0 expires typically after one hour. If you simply re-run the redirect script every time, users will have to log in repeatedly.

Best practice involves saving the $token array (which includes access_token, refresh_token, and expires_in) to a local file or database immediately after the first successful login. On subsequent requests, check if the token is still valid. If it has expired (or if you have no token), use the refresh_token to obtain a new access token without requiring user interaction again.

Alternative: Service Accounts for Server-to-Server Access

If your application runs on a server where user login is not required, or if you need to read spreadsheets owned by your own service rather than individual users, consider using a Service Account. This approach bypasses the browser-based OAuth flow entirely.

You would download the JSON key from the Google Cloud Console under "IAM & Admin" > "Service Accounts". You can then use the google-api-php-client to initialize the client with this private key instead of credentials:

$client = new Google_Client();
$client->setApplicationName('My Spreadsheet Reader');
$client->setScopes(['https://www.googleapis.com/auth/drive.readonly']);

// Load the service account credentials
$credentials = json_decode(file_get_contents('path/to/credentials.json'), true);
$client->setAuthConfig($credentials); // Or use setServiceAccountCredentials if using older library versions

// Initialize the Drive service
$service = new Google_DriveService($client);

try {
    $file = $service->files->get('YOUR_FILE_ID');
    echo "Title: " . $file->getTitle();
} catch (Exception $e) {
    // Handle exceptions
}

Trade-off Warning: Service Accounts have strict limitations. You generally cannot use them to read files owned by other users, only those shared explicitly with the service account's email address or your own project files. For most web applications reading user data, the standard OAuth 2.0 flow described first is the correct choice.

Final Configuration Checklist

Before expecting the API calls to work, verify these specific details:

  1. Redirect URI Match: Ensure the string in $client->setRedirectUri() matches the "Authorized redirect URIs" field in your Google API Console exactly, including http vs https.
  2. Scope Selection: You don't need all five scopes defined in your original code (drive, drive.apps.readonly, etc.). For reading a file, 'https://www.googleapis.com/auth/drive.file' is usually sufficient and follows the principle of least privilege.
  3. File ID vs Share Link Key: The variable you labeled as GDRIVE_FILE_KEY should be the unique File ID found in the Google Drive API details page (e.g., 0B1...), not a share link URL parameter.

By completing the OAuth handshake and managing token expiration, your application will move past the 403 limit error and successfully read your Google Sheets data.

Our network