Best way to use Google Analytics (GA4) Realtime API with PHP


Google Analytics 4 (GA4) is the latest version of Google’s web analytics platform, designed to provide more comprehensive and actionable insights into user behavior across websites and apps.

  • Event-based Tracking: GA4 captures every user interaction as an individual event for more detailed data analysis.
  • Cross-platform Tracking: GA4 provides a unified view of user behavior across websites and mobile apps.
  • User-centric Reporting: GA4 focuses on users and their interactions over multiple sessions for a holistic view of behavior.
  • Machine Learning Insights: GA4 utilizes Google’s AI to highlight trends, anomalies, and provide predictive analytics.
  • Privacy and Compliance: GA4 is designed with data privacy in mind, offering granular data controls for compliance with laws like GDPR and CCPA.
  • Simplified Goals and Conversion Tracking: GA4 offers easier setup and management of goals and conversion events without code changes.

Google Analytics GA4

We had provided a tutorial on Google Analytics Realtime Api for older version earlier. In this tutorial, we are going to develop a complete Google Analytics (GA4) Realtime Traffic Tracking tool using Analytics API.

GA4 Realtime API

Step 1 : Create composer.json file with following code


    "require": {
        "google/apiclient": "^2.16"

Step 2 : Run composer install command

composer install

Follow this video for complete guidance :

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

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.

ALSO READ  Get Client IP Address using PHP

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

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

<link rel="stylesheet" href="">
<script type="text/javascript" src=""></script>

<style type="text/css">
    font-size: 50px;
    background: #ddd;
    cursor: pointer;
     background: aliceblue;
     background: #2285ef;
     height: 50px;
     display: flex;
     align-items: center;
     justify-content: center;
     color: #fff;
     font-size: 18px;
    margin-top: 20px;
    cursor: pointer;
    font-size: 25px;
    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;
      text-align: center;
  .progress {
    display: flex;
    position: absolute;
      text-align: center;
      width: inherit;
      padding-top: 5px;
    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}
  	align-items: center;
  	justify-content: center;
  .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;


<div class="container page-content">
  <div class="row">
    <div class="col-md-8">
    <table class="table table-bordered" id="result-pages">
          <th width="40%">Top Active Pages</th>
    <div class="col-md-4">
  		<table class="table table-bordered">
                	<th>Right Now</th>
                            <div class="count" id="active-users">
                      	<p>Active Users on Site</p>
                      		<div class="progress-label" style="display:flex;">
      							<div class="label label-warning">
      							<div class="label label-success">
      							<div class="label label-danger">
      						<div id="devices">

      	<table class="table table-bordered" id="countries-sources">


<script type="text/javascript">
  function getDeviceColor(device){
      return 'warning';
      return 'success';
      return 'danger';
 	function getData(){
 				pages = country = devices = '';
 				res = $.parseJSON(res);
 				//active pages
 				for(var i=0;i<res['title'].length;i++){
 					pages += '<tr class="open-link" data-link="">';
              pages += '<td>'+res['title'][i]['unifiedScreenName']+'</td>';
              pages += '<td>'+res['title'][i]['active_users']+'</td>';
            pages += '</tr>';
            $("#result-pages tbody").html(pages);

            total_users = res['device'].length;
            devices += '<div class="progress" style="width:100%!important">';
            for(var i=0;i<res['device'].length;i++){
            	percent = (res['device'][i]['active_users']/total_users)*100;
            	devices += '<div class="progress-bar progress-bar-'+getDeviceColor(res['device'][i]['deviceCategory'])+'" style="width:'+percent+'%">'+res['device'][i]['active_users']+'</div>';
        devices += '</div>';


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

require 'vendor/autoload.php';

use Google\Client;
use Google\Service\AnalyticsData;

// Path to the service account key file
$serviceAccountPath = 'SERVICE_ACCOUNT.json';

// Property ID for GA4
$propertyId = 'PROPERTY_ID';

// Initialize the Google Client
$client = new Client();

function getData($analyticsData,$propertyId, $dimension){
  $requestBody = new AnalyticsData\RunRealtimeReportRequest([
      'dimensions' => [
          ['name' => $dimension],       // Active pages or country
      'metrics' => [
          ['name' => 'activeUsers'],     // Active users metric

  // Fetch the real-time report
  $response = $analyticsData->properties->runRealtimeReport(
  foreach ($response->getRows() as $row) {
      $dimensions = $row->getDimensionValues();
      $metrics = $row->getMetricValues();
      $data[] = [
          $dimension => $dimensions[0]->getValue(),
          'active_users' => $metrics[0]->getValue()
  return $data;

// Initialize the Analytics Data service
$analyticsData = new AnalyticsData($client);

$response['title'] = getData($analyticsData,$propertyId,'unifiedScreenName');
$response['device'] = getData($analyticsData,$propertyId,'deviceCategory'); 
$response['country'] = getData($analyticsData,$propertyId,'country'); 
echo json_encode($response);


Don’t forget to update these two lines with proper values of your service account json file and Google Analytics Property ID.

ALSO READ  How to Zip/Unzip files using PHP

$serviceAccountPath = ‘SERVICE_ACCOUNT.json’;

$propertyId = ‘PROPERTY_ID’;

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


Comments are closed.