Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
* 1. create project at
* 2. enable 'Analytics API' under 'APIs & auth' / APIs
* 3. create 'NEW CLIENT ID' (OAuth client) under 'APIs & auth' / Credentials
* i. select 'Service account'
* ii. save generated key file to 'key.p12'
* iii. remember CLIENT ID
* 4. under GA account add 'Read & Analyze' access to newly generated email (access to GA Account not Property nor View)
* 5. get View ID. go to GA Admin section, select proper Account, than proper Property, than proper View.
Under View click on 'View settings' and copy the number below 'View ID' (that is your GA_VIEW_ID number)
* 5. download google php library
* 6. use the code below, use info from google API console (1.)
* doc here:
* real time metrics doc:
set_include_path('src/' . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$CLIENT_ID = '';
$SCOPE = '';
$KEY_FILE = 'key.p12';
$GA_VIEW_ID = 'ga:ZZZ';
$client = new Google_Client();
new Google_Auth_AssertionCredentials(
$service = new Google_Service_Analytics($client);
try {
$result = $service->data_realtime->get(
} catch(Exception $e) {

gubertu commented Jun 12, 2014

it's works after and changed the timezone in php.ini!!

thanks! :)

Great job, thank you so much!

For those getting the following error: "Fatal error: Class 'Google_Service' not found"
use the autoload.php instead:

require_once 'Google/autoload.php';

THANK YOU! Would have saved me 5 hours if I found this earlier.

it's give white page

I needed to figure this out the other day and ended up writing a blog-post with a detailed description on how to get to the rt:activeVisitors with PHP. Hope that helps someone out there.

Warning: require_once(Google/Service/Analytics.php): failed to open stream:

help me


ghost commented Apr 7, 2017

use this:
<?php //Google RealTime Connect require_once 'path_to/vendor/autoload.php'; $client = new Google_Client(); $client->setApplicationName("XXXX"); // your project name $client->setAuthConfig('path_to_Auth_jsno_file'); $client->addScope(''); $GA_VIEW_ID = 'ga:XXXX'; // your View_ID $service = new Google_Service_Analytics($client); try { $result = $service->data_realtime->get( $GA_VIEW_ID, 'rt:activeVisitors' ); $count = $result->totalsForAllResults['rt:activeVisitors']; echo $count; } catch(Exception $e) { var_dump($e);

umh commented Jul 24, 2017

Hi, i wanna know whether we can?:

  1. Display total page views (lifetime data) for a specific page
  2. Display current active users on a page.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment