Using OAuth 2.0 to Access Google APIs with PHP

This example shows how to create a PHP based application on your web server that uses OAuth 2.0 authorization to access the various Google APIs include Gmail, Google Drive, Google Admin SDK and more. You can either use your local machine (localhost:8000) or a live server for application development.

To get started, go to Google Developer’s console and create a new project. For this example we are sending email through Gmail so need to enable the Gmail API. Next click on credentials, New Client Credentials, Create Client ID (set the application type as Other) and make a note of the client id and client secret.

Start the local HTTP Server – open the Mac terminal and write php -S localhost:8000to start the development server. You should do this in the local directory containing the PHP files. Open the php file from your browser and it will redirect you to the consent screen. Once you have authorized, the Google OAuth 2.0 server will provide that authorization code that the application will pass to the Google Server (with the client secret) to obtain the access token. You can then use this access token to access various Google APIs.