Google Analytics api – Google Analytics how to add php website

Spread the love

Google Analytics api – Google Analytics how to add php website: For visitor tracking, visitor, analytics for website, page counter, page view, real time visitor tracking, traffic sources etc.

Friends welcome you to another new article on the blogging post website. In the short paragraph above we find out what we are going to discuss today and how to connecting it to our php website.

Also read: How to send emails from php | php से ईमेल कैसे भेजें

Also Read: Google Swag Shop | Google Gift Shop

This is a very simple method. Using this method, we can see the live report of Google Analytics on our website without opening our Google Analytics account. Google Analytics has provided us with this facility using Google Analytics api.

If you are a student of Computer Science or if you are a student of BCA , MCA then it will play a very important role as your University , College final year project. If you want, you can make it as a final year project of your University or College .

There are seven different steps for you to do this whole set. We will discuss these seven very important things below so read this article carefully. We will discuss these seven steps one by one to help us for better understand.

Google Analytics how to connecting php website

So friends in this articale, we are going to develop a complete Google Analytics api Realtime Traffic Tracking, visitor tracking, visitor, analytics for website, page counter, page view, real time visitor tracking, traffic sources tool using Analytics API.

Friends follow these steps by steps to develop your own Google Analytics Dashboard for Realtime tracking.

Step 1 : Create composer.json file using following code for (./vendor/autoload.php)

Create a file and name it “composer.json”. in your localhost server. For example – xampp, wamp its are localhost server. They can run php code in your pc.

Copy following code and paste this code in the composer.json file and save it.

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

Step 2 : Run composer install command in your pc or laptop (command prompt)

Click start menu -> then Click search box and enter command prompt -> Now click command prompt software.

command prompt
command prompt

Now select your localhost drive -> select your folder where you want to create “vendor library“. -> enter the composer install command in command prompt -> then press enter. Wait some time while you not get success message to vendor library created successfully.

Step 3 : Create Google Developers Console Account

Now you need to create Google Developers Console account, for “Google Analytics API” and “Enable” Analytics API for working Google Analytics php.

You will need to login with the email id you used to create your Google Analytics account. when you login your Google Developers Console Account will be created automatically.

select cuontry name and terms of service click Agree and continue
select country name and terms of service click Agree and continue

Now select your Country Name -> and tick the Terms of Service below -> then click the Agree and continue button.

Also Read: Insert html form Data to mysqli Database using PHP

Google Analytics API now we need to Create a Project in our Google Developers Console Account. Click the Create Project option on the right side of your Google Developers Console Account dashboard.

create project
create project

You can give the name of the project if you want, otherwise you can use the name of the project provided by Google. -> Now click on the Create button.

create your new project
create your new project

Wait a while after clicking the Create button. Once the project is created it will take you directly to the credentials page.

Now we need to create a service account. To create this service account click on the Manage service accounts option at the bottom right.

Manage service accounts

Click the Create Service Account option from the menu bar option at the top of your Google Developers Console Account dashboard. Name the service account of your choice -> then click on Create and Continue option -> then click on Done option.

Service account details Google Analytics api
Service account details

As soon as you click the Done button, your service account will be created and you will see it on your dashboard.

account created successfully
account created successfully

Now click on your service account email ID for creating for generating KEYS. click on KEYS option from the tab.

keys
KEYS

Click ADD KEY option -> then click Create New Key option.

ADD KEY Google Analytics api
ADD KEY

After clicking on Create New Key option a new window will open where you have to select key type, select Key type JSON and click on Create.

select key types
select key types

When you click create button Private key saved to your computer automatically. The file will be downloaded to your computer in Jason format.

Private key saved to your computer Google Analytics api
Private key saved to your computer

Also Read: Make IFSC Details Website Using API and PHP – AdSense Earn money

Now open the downloaded JSON file and from there you can see the service email id and copy it. Then open your Google Analytics account with the same email ID. The email id you used to create your Google Developers Console Account.

Service account email
Service account email

Now you need to add your service account email id to the property of Google Analytics, of which you want to access the Realtime data.

Now open your Google Analytics account -> click Admin settings ->then select Property -> click Property access management -> then click add users top of the right side in the analytics dashboard Property access management page -> Now paste the service account email id you copied from your JSON file here then click on ADD option.

Property access management add service email id
Property access management add service email id

Step 5 : Create index.php file to show the realtime traffic along with bellow source and devices

Now you create a folder in the “xampp/htdocs” folder on your localhost server. For example, I named the folder here GA Google Analytics. Now copy and paste the folder where you created your vendor folder i.e. which you created the vendor library, using Run composer install command into this root folder.

index.php

Save the index.php file to your root folder by copying the complete codes below and creating a file called 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 in root folder Google Analytics api

functions.php

create functions.php file and copy the below code then paste it and save in root folder. In my case root folder name is GA Google Analytics.

you must be need to change something in your functions.php file

  1. define(‘VIEW’,’998985989′); // here enter your Google Analytics property view ID.
  2. define(‘SERVICE_ACCOUNT’,’pro-flux-*****-12cf37e9c49e’); // here your downloaded JSON file name from Google Developers Console Account.
  3. define(‘DOMAIN’,’https://yourdomain.com’); // Enter your domain name.
<?php

define('VIEW','998985989'); // here enter your Google Analytics property view ID
define('SERVICE_ACCOUNT','pro-flux-*****-12cf37e9c49e'); // here your downloaded JSON file name from Google Developers Console Account.
define('DOMAIN','https://yourdomain.com'); //  Enter your domain name.


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 : Final step Create ajax.php file Google Analytics api

Create ajax.php file. copy below code and paste it in your ajax.php file and then save it in root folder.

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);
  }
}

How to find Google Analytics property View id?

Open your Google Analytics account -> then click admin user settings -> then select property click to view settings then you can see your property VIEW ID.

GA view id Google Analytics api
GA view id

Also Read: Best Web Hosting for WordPress Cheap with Great Performance

Click to view settings then you can see your property VIEW ID.

View ID Google Analytics api
View ID

Now you can run your Google Analytics API real time data all script in your browser. just enter your local server root folder URL in your browser and enter. In my case url is – localhost/GA.

The last few words

Friends, I hope you enjoyed today’s article. You must share this article with your family and friends.

If you have any problems with this article please let us know in the comment box and we will try to resolve your comment as soon as possible.

If you have any problems using these codes, that is, if the codes do not work properly, you must let us know in the comment box. We will try to correct your code as soon as possible.


Spread the love

Leave a Comment