<?php
require_once 'google-api-php-client/src/Google/autoload.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('name');
$client->setClientId('id');
$client->setClientSecret('password');
$client->setRedirectUri('URL');
$client->setScopes("https://www.googleapis.com/auth/analytics.readonly");
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if($client->isAccessTokenExpired()) {
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}
if (!$client->getAccessToken()) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$service = new Google_Service_Analytics($client);
$id = 'ga:xxxxx' ;
$start_date = '2010-01-01';
$end_date = 'today';
$metrics = "ga:pageviews";
$total = $service->data_ga->get($id,$start_date,$end_date,$metrics);
$rows = $total->getRows() ;
$sessions = $rows[0][0];
echo $sessions ;
}