Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

PHP

Google Analytics Realtime Traffic Viewer using Analytics API

By Admin
September 11, 2021 4 Min Read
0

In this tutorial, we are going to develop a complete Google Analytics Realtime Traffic Tracking tool using Analytics API.

UPDATE : New tutorial is made for GA4 Realtime API : https://youthsforum.com/programming/php/google-analytics-ga4-realtime-api-using-php/

Please follow these steps to develop your own Google Analytics Dashboard for Realtime Traffic tracking.

Step 1 : Create composer.json file with following code

composer.json

{
  "require": {
    "google/apiclient": "^2.0"
  }
}

Step 2 : Run composer install command

composer install

Step 3 : Go to Google Developers Console and create a new project

Then, enable Google Analytics API. Under Credentials menu, click on Manage Service Accounts. Now create a new Service Account.
Click on the newly created service account and then navigate to Keys tab and then create new key of type JSON. A JSON file will be downloaded. Place the downloaded JSON file in the root of your project.

Step 4 : Open the JSON file

Find the email address of the service account in it. Now add that email address as the user of the analytics property of which you want ot access the realtime data in analytics.google.com

Step 5 : Create a view to show the realtime traffic along with source and devices

index.php

<?php include_once('functions.php');?>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>

<style type="text/css">
  .count{
    font-size: 50px;
  }
  .open-link:hover{
    background: #ddd;
    cursor: pointer;
  }
 	body{
 		background: aliceblue;
 	}
 	.header{
 		background: #2285ef;
 		height: 50px;
 		display: flex;
 		align-items: center;
 		justify-content: center;
 		color: #fff;
 		font-size: 18px;
 	}
  .page-content{
    margin-top: 20px;
  }
  .site-name{
    cursor: pointer;
    font-size: 25px;
  }
  
  .site-list{
    display: none;
    position: absolute;
    padding: 30px;
    background: #ddd;
    top: 50px;
    z-index: 100;
    background: #000;
    padding: 0px;
  }
  table {
    background: #fff;
    -webkit-box-shadow: 0px 0px 5px -1px rgba(158,155,158,1);
    -moz-box-shadow: 0px 0px 5px -1px rgba(158,155,158,1);
    box-shadow: 0px 0px 5px -1px rgba(158,155,158,1);
    padding-bottom: 15px;
  }
  h1,p{
  		text-align: center;
  }
  .progress {
    display: flex;
  }
  .progress-cotent{
    position: absolute;
      text-align: center;
      width: inherit;
      padding-top: 5px;
  }
  .count{
    font-size: 86px;
  }
  .progress-bar-success, .label-success:before {background-color: #50b432;}
  .progress-bar-warning, .label-warning:before {background-color: #ed561b;}
  .progress-bar-danger, .label-danger:before {background-color: #058dc7;}
  .label-success, .label-warning, .label-danger{background: transparent;color: #444;display: inline-block;font-size: 1em;line-height: 1.1em;font-weight: bold;font-family: arial;}
  .progress-label .label:before{content:'';width:10px; height:10px;float:left; margin-right:3px;}
  .progress-bar-danger span, .label-success span + span, .label-warning span + span{}
  .progress-label{text-transform:uppercase;font-size:0.8em; font-weight:bold;margin:5px 0 8px}
  .table{border-radius:5px 5px 0 0;box-shadow:inherit; -webkit-box-shadow:inherit; border-top:2px solid #666}
  .table  th{background:#fff;padding:10px 8px; height:auto;font-size:0.95em;}
  .table tr:nth-child(odd) td:nth-child(even) { background: rgba(0,0,0,0.03);text-align:center;}
  .table tr:nth-child(even) td { background: rgba(0,0,0,0.02)}
  .table tr:nth-child(even) td:nth-child(even) { background: rgba(0,0,0,0.06);text-align:center;}
  .table>tbody>tr>td{padding:7px 8px;color:#444; font-size:0.95em;}
  .table td{width:90%}
  .table td:nth-child(even){width:10%;}
  .col-md-3 .table td{width:64%}
  .col-md-3 .table td:nth-child(even){width:36%;}
  @media (max-width:768px){
    .col-md-9, .col-md-3{padding:0}
  }
  @media (max-width: 991px) {
      .col-md-3.pull-right {
          float: none !important;
      }
  }
</style>



<div class="container page-content">
  <div class="row">
    <div class="col-md-8">
      <table class="table table-bordered" id="result-pages">
        <thead>
          <tr>
            <th width="40%">Top Active Pages</th>
            <th>Users</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
    <div class="col-md-4">
      <table class="table table-bordered">
            	<tbody>
            		<tr>
              			<th>Right Now</th>
        			</tr>
            		<tr>
              			<td>
                			<h1>
                                <div class="count" id="active-users">
                                </div>
                			</h1>
                			<p>Active Users on Site</p>
                			<br>
                			<div id="devices">
           					</div>
        				</td>
        			</tr>
      			</tbody>
      		</table>
      		
      		<table class="table table-bordered" id="result-sources">
      			<thead>
      				<tr>
      					<th>Source</th>
      					<th>Users</th>
      				</tr>
      			</thead>
      			<tbody>
      			</tbody>
      		</table>
      		
      		<table class="table table-bordered" id="countries-sources">
      			<thead>
      				<tr>
      					<th>Country</th>
      					<th>Users</th>
      				</tr>
      			</thead>
      			<tbody>

      			</tbody>
      		</table>

      		<table class="table table-bordered" id="browser-sources">
      			<thead>
      				<tr>
      					<th>Browser</th>
      					<th>Users</th>
      				</tr>
      			</thead>
      			<tbody>
      			</tbody>
      		</table>
      		<table class="table table-bordered" id="os-sources">
      			<thead>
      				<tr>
      					<th>OS</th>
      					<th>Users</th>
      				</tr>
      			</thead>
      			<tbody>
      			</tbody>
      		</table>
      		
    </div>
  </div>
</div>

<script type="text/javascript">
  setInterval(function(){
    call();
  },5000);

  function call(){
    get('pages');
    get('users');
    get('devices');
    get('sources');
    get('countries');
    get('browser');
    get('os');
  }
  call();

  function get(action){
    var view = '<?php echo VIEW;?>';
    $.ajax({
      url:"ajax.php?action="+action+'&view='+view,
      type:'get',
      success:function(res){
        if(action=='pages'){
          $("#result-pages tbody").html(res);
        }
        else if(action=='users'){
          $("#active-users").html(res);
        }
        else if(action=='devices'){
          $("#devices").html(res);
        }
        else if(action=='sources'){
          $("#result-sources tbody").html(res);
        }
        else if(action=='countries'){
          $("#countries-sources tbody").html(res);
        }
        else if(action=='browser'){
          $("#browser-sources tbody").html(res);
        }
        else if(action=='os'){
          $("#os-sources tbody").html(res);
        }
      }
    });
  }

  $(document).on('click','.open-link',function(){
    link = $(this).attr('data-link');
    link = '<?php echo DOMAIN;?>'+link;
    window.open(link, '_blank');
  });
</script>

Step 6 : Create functions.php file

functions.php

<?php

define('VIEW','194594240');
define('SERVICE_ACCOUNT','analytics-325704-1b0b324a12d4.json');
define('DOMAIN','https://reeteshghimire.com.np');


function getActivePages($analytics){
  $optParams = array(
    'dimensions' => 'rt:pageTitle,rt:pagePath',
    'sort' => '-rt:activeVisitors',
    'max-results' => '16'
  );
  $result = $analytics
        ->data_realtime
        ->get('ga:'.VIEW, 'rt:activeVisitors',$optParams);

  $table = '';
  if($result){
    $rows = $result->getRows();
    if($rows){
      foreach($rows as $row){
        $table .= '<tr class="open-link" data-link="'.$row[1].'">';
        $table .= '<td>'.htmlspecialchars($row[0],ENT_NOQUOTES).'</td>';
        $table .= '<td>'.htmlspecialchars($row[2],ENT_NOQUOTES).'</td>';
        $table .= '</tr>';
      }
    }else{
      $table .= '<tr><td colspan="2"><small>There is no data to view</small></td></tr>';
    }
    return $table;
  }else{
    return '<tr><td colspan="2"><small>There is no data to view</small></td></tr>';
  }
}

function getActiveUsers($analytics){
  $active_users = $analytics
          ->data_realtime
          ->get('ga:'.VIEW, 'rt:activeVisitors');
  $active_users = (isset($active_users->rows[0][0]))?$active_users->rows[0][0]:0;
  return $active_users;
}

function getDevices($analytics){
  $optParams = array(
    'dimensions' => 'rt:deviceCategory',
    'sort' => '-rt:activeVisitors'
  );

  $devices = $analytics
        ->data_realtime
        ->get('ga:'.VIEW, 'rt:activeVisitors',$optParams);
  $html = '';
  if($devices->rows){
    $total = 0;
    $class = array('warning','success','danger');
    foreach($devices->rows as $row){
      $total += $row[1];
    }
    $loop = 0;
    $html .= '<div class="progress_label">';
    foreach($devices->rows as $row){
      $percent = round(($row[1]/$total)*100);
      $html .= '<div class="label label-'.$class[$loop].'">';
      $html .= '<span>'.$row[0].'</span>';
      $html .= '<span>'.$row[1].'</span>';
      $html .= '</div>';
      $loop++;
    }
    $html .= '</div>';
    $loop = 0;
    $html .= '<div class="progress" style="width:100%!important">';
    foreach($devices->rows as $row){
      $html .= '<div class="progress-bar progress-bar-'.$class[$loop].'" style="width:'.$percent.'%"></div>';
      $loop++;
    }
    $html .= '</div>';
  }
  return $html;
}


function getFormattedData($result){
  $table = '';
  if($result){
    $rows = $result->getRows();
    if($rows){
      foreach($rows as $row){
        $table .= '<tr>';
        foreach($row as $cell){
          $table .= '<td>'.htmlspecialchars($cell,ENT_NOQUOTES).'</td>';
        }
        $table .= '</tr>';
      }
    }else{
      $table .= '<tr><td colspan="2"><small>There is no data to view</small></td></tr>';
    }
    return $table;
  }else{
    return '<tr><td colspan="2"><small>There is no data to view</small></td></tr>';
  }
}

function getTrafficSources($analytics){
  $optParams = array(
    'dimensions' => 'rt:source',
    'sort' => '-rt:activeVisitors',
    'max-results' => 5
  );

  $result = $analytics
        ->data_realtime
        ->get('ga:'.VIEW,'rt:activeVisitors',$optParams);
  return getFormattedData($result);
}

function getCountries($analytics){
  $optParams = array(
    'dimensions' => 'ga:country',
    'sort' => '-rt:activeVisitors',
    'max-results' => 10
  );

  $result = $analytics
        ->data_realtime
        ->get('ga:'.VIEW,'rt:activeVisitors',$optParams);
  return getFormattedData($result,'Country','Users');
}


function getOS($analytics){
  $optParams = array(
    'dimensions' => 'ga:operatingSystem',
    'sort' => '-rt:activeVisitors',
    'max-results' => 10
  );

  $result = $analytics
        ->data_realtime
        ->get('ga:'.VIEW,'rt:activeVisitors',$optParams);
  return getFormattedData($result,'OS','Users');
}


function getBrowser($analytics){
  $optParams = array(
    'dimensions' => 'ga:browser',
    'sort' => '-rt:activeVisitors',
    'max-results' => 10
  );

  $result = $analytics
        ->data_realtime
        ->get('ga:'.VIEW,'rt:activeVisitors',$optParams);
  return getFormattedData($result,'Browser','Users');
}

Step 7 : Create ajax.php file

ajax.php

<?php 

include('functions.php');

//initialize analytics
require_once __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName("Realtime Analytics");
$client->setAuthConfig(SERVICE_ACCOUNT);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);

if(isset($_GET['action'])){
  $action = $_GET['action'];
  if($action=='pages'){
    echo getActivePages($analytics);
  }
  elseif($action=='users'){
    echo getActiveUsers($analytics);
  }
  elseif($action=='devices'){
    echo getDevices($analytics);
  }
  elseif($action=='sources'){
    echo getTrafficSources($analytics);
  }
  elseif($action=='countries'){
    echo getCountries($analytics);
  }
  elseif($action=='os'){
    echo getOS($analytics);
  }
  elseif($action=='browsers'){
    echo getBrowser($analytics);
  }
}

 

That’s it. Now browse your project from your browser and track realtime traffic in your site.

CHEERSSSS

Tags:

analyticsAPIPHP
Author

Admin

Follow Me
Other Articles
Previous

Live Code Editor using HTML, CSS and JavaScript

Next

BS / AD Date Converter using PHP

No Comment! Be the first one.

Leave a Reply

Your email address will not be published. Required fields are marked *

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme