Connect to Google API with PHP and OAuth2 - Sample Code

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/>';

Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

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.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory


Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.