Connect to Google API with PHP and OAuth2 - Sample Code

Published in: Gmail - Google Cloud - PHP

This sample application describes how your PHP application can connect to the user’s Gmail account using the Google PHP client library and OAuth2. You’ll need to create the application inside Google Console.

The Client ID and secret are stored in a separate JSON while the access token and refresh token are also stored in the local file system.

  require_once __DIR__ . '/vendor/autoload.php';

  $REDIRECT_URI = 'http://localhost:8080';
  $KEY_LOCATION = __DIR__ . '/client_secret.json';
  $TOKEN_FILE   = "token.txt";

  $SCOPES = array(

  $client = new Google_Client();
  $client->setApplicationName(" Application");

  // Incremental authorization

  // Allow access to Google API when the user is not present.

  if (isset($_GET['code']) && !empty($_GET['code'])) {
      try {
          // Exchange the one-time authorization code for an access token
          $accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);

          // Save the access token and refresh token in local filesystem
          file_put_contents($TOKEN_FILE, json_encode($accessToken));

          $_SESSION['accessToken'] = $accessToken;
          header('Location: ' . filter_var($REDIRECT_URI, FILTER_SANITIZE_URL));
      catch (\Google_Service_Exception $e) {

  if (!isset($_SESSION['accessToken'])) {

      $token = @file_get_contents($TOKEN_FILE);

      if ($token == null) {

          // Generate a URL to request access from Google's OAuth 2.0 server:
          $authUrl = $client->createAuthUrl();

          // Redirect the user to Google's OAuth server
          header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));

      } else {

          $_SESSION['accessToken'] = json_decode($token, true);



  /* Refresh token when expired */
  if ($client->isAccessTokenExpired()) {
      // the new access token comes with a refresh token as well
      file_put_contents($TOKEN_FILE, json_encode($client->getAccessToken()));

  $gmail = new Google_Service_Gmail($client);

  $opt_param               = array();
  $opt_param['maxResults'] = 10;

  $threads = $gmail->users_threads->listUsersThreads("", $opt_param);

  foreach ($threads as $thread) {
      print $thread->getId() . " - " . $thread->getSnippet() . '<br/>';

Published in: Gmail - Google Cloud - PHP

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch