PHPackages                             johnkarpn/php-ga-measurement-protocol - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. johnkarpn/php-ga-measurement-protocol

ActiveLibrary[API Development](/categories/api)

johnkarpn/php-ga-measurement-protocol
=====================================

Send data to Google Analytics from the server using PHP. This library fully implements GA measurement protocol.

v2.9.3(2y ago)01.4k↑28.1%MITPHPPHP &gt;=7.3

Since Sep 23Pushed 2y agoCompare

[ Source](https://github.com/johnkarpn/php-ga-measurement-protocol)[ Packagist](https://packagist.org/packages/johnkarpn/php-ga-measurement-protocol)[ RSS](/packages/johnkarpn-php-ga-measurement-protocol/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (32)Used By (0)

Google Analytics Measurement Protocol library for PHP
=====================================================

[](#google-analytics-measurement-protocol-library-for-php)

[![packagist](https://camo.githubusercontent.com/2a16f21914b37c20fc6b1b103a0970ddf41e30e54245f29bcf46b7c3689caa89/687474703a2f2f706f7365722e707567782e6f72672f6a6f686e6b6172706e2f7068702d67612d6d6561737572656d656e742d70726f746f636f6c2f76)](https://packagist.org/packages/johnkarpn/php-ga-measurement-protocol)[![downloads](https://camo.githubusercontent.com/cf22c1bae8ea53bb6e65e7836ce085a7d76eff37e1952d9b89ca46a8a176fe15/687474703a2f2f706f7365722e707567782e6f72672f6a6f686e6b6172706e2f7068702d67612d6d6561737572656d656e742d70726f746f636f6c2f646f776e6c6f616473)](https://packagist.org/packages/johnkarpn/php-ga-measurement-protocol)[![min php version](https://camo.githubusercontent.com/19dc36f9bd32827c3a9536ef9596c36a5acd92882960436bc37c12bac97d4914/687474703a2f2f706f7365722e707567782e6f72672f6a6f686e6b6172706e2f7068702d67612d6d6561737572656d656e742d70726f746f636f6c2f726571756972652f706870)](https://packagist.org/packages/johnkarpn/php-ga-measurement-protocol)[![license](https://camo.githubusercontent.com/2e969bd02a771e55190363e7aa61ef0b6c07d206bd690d7432fe9cf75667fc9b/687474703a2f2f706f7365722e707567782e6f72672f6a6f686e6b6172706e2f7068702d67612d6d6561737572656d656e742d70726f746f636f6c2f6c6963656e7365)](https://packagist.org/packages/johnkarpn/php-ga-measurement-protocol)[![tests](https://github.com/johnkarpn/php-ga-measurement-protocol/actions/workflows/tests.yml/badge.svg)](https://github.com/johnkarpn/php-ga-measurement-protocol/actions/workflows/tests.yml)[![code coverage badge](https://raw.githubusercontent.com/johnkarpn/php-ga-measurement-protocol/image-data/coverage.svg)](https://raw.githubusercontent.com/johnkarpn/php-ga-measurement-protocol/image-data/coverage.svg)[![lines of code](https://raw.githubusercontent.com/johnkarpn/php-ga-measurement-protocol/image-data/lines.svg)](https://raw.githubusercontent.com/johnkarpn/php-ga-measurement-protocol/image-data/lines.svg)

This is a fork of the original no longer maintained project . There are no plans to add support for Google Analytics 4, this package is maintenance only for php 8.x support.

Description
-----------

[](#description)

Send data to Google Analytics from the server using PHP. This library fully implements GA measurement protocol so its possible to send any data that you would usually do from analytics.js on the client side. You can send data regarding the following parameters categories [(Full List)](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters):

- General
- User
- Session
- Traffic Sources
- System Info
- Hit
- Content Information
- App Tracking
- Event Tracking
- E-Commerce
- Enhanced E-Commerce
- Social Interactions
- Timing
- Exceptions
- Custom Dimensions / Metrics
- Content Experiments
- Content Grouping

Installation
------------

[](#installation)

Use Composer to install this package.

```
composer require johnkarpn/php-ga-measurement-protocol

```

Integrations
------------

[](#integrations)

You can use this package on its own, or use a convenient framework integration:

- Laravel 5+ -
- Yii 2 -
- Symfony2 -

Feel free to create an integration with your favourite framework, let us know so we list it here.

Usage
-----

[](#usage)

The required parameters for all hits are Protocol Version, Tracking ID and at least one of these: Client ID or User ID. Some optional ones like IP Override are recommended if you don't want all hits to seem like coming from your servers.

```
use TheIconic\Tracking\GoogleAnalytics\Analytics;

// Instantiate the Analytics object
// optionally pass TRUE in the constructor if you want to connect using HTTPS
$analytics = new Analytics(true);

// Build the GA hit using the Analytics class methods
// they should Autocomplete if you use a PHP IDE
$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-26293728-11')
    ->setClientId('12345678')
    ->setDocumentPath('/mypage')
    ->setIpOverride("202.126.106.175");

// When you finish bulding the payload send a hit (such as an pageview or event)
$analytics->sendPageview();
```

The hit should have arrived to the GA property UA-26293728-11. You can verify this in your Real Time dashboard. Take notice, if you need GA reports to tie this event with previous user actions you must get and set the ClientId to be same as the GA Cookie. Read ([here](https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#getting_the_client_id_from_the_cookie)).

The library is 100% done, full documentation is a work in progress, but basically all parameters can be set the same way.

```
// Look at the parameter names in Google official docs at
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
$analytics->set('my_value');
```

```
// Get any parameter by its name
// Look at the parameter names in Google official docs at
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
$analytics->get();
```

All methods for setting parameters should **Autocomplete** if you use an IDE such as PHPStorm, which makes building the Analytics object very easy.

Use Cases
---------

[](#use-cases)

### Order Tracking with simple E-commerce

[](#order-tracking-with-simple-e-commerce)

```
use TheIconic\Tracking\GoogleAnalytics\Analytics;

$analytics = new Analytics();

// Build the order data programmatically, including each order product in the payload
// Take notice, if you want GA reports to tie this event with previous user actions
// you must get and set the same ClientId from the GA Cookie
// First, general and required hit data
$analytics->setProtocolVersion('1')
    ->setTrackingId('UA-26293624-12')
    ->setClientId('2133506694.1448249699');

// To report an order we need to make single hit of type 'transaction' and a hit of
// type 'item' for every item purchased. Just like analytics.js would do when
// tracking e-commerce from JavaScript
$analytics->setTransactionId(1667) // transaction id. required
    ->setRevenue(65.00)
    ->setShipping(5.00)
    ->setTax(10.83)
    // make the 'transaction' hit
    ->sendTransaction();

foreach ($cartProducts as $cartProduct) {
    $response = $analytics->setTransactionId(1667) // transaction id. required, same value as above
        ->setItemName($cartProduct->name) // required
        ->setItemCode($cartProduct->code) // SKU or id
        ->setItemCategory($cartProduct->category) // item variation: category, size, color etc.
        ->setItemPrice($cartProduct->price)
        ->setItemQuantity($cartProduct->qty)
        // make the 'item' hit
        ->sendItem();
}
```

### Order Tracking with Enhanced E-commerce

[](#order-tracking-with-enhanced-e-commerce)

```
use TheIconic\Tracking\GoogleAnalytics\Analytics;

$analytics = new Analytics();

// Build the order data programmatically, including each order product in the payload
// Take notice, if you want GA reports to tie this event with previous user actions
// you must get and set the same ClientId from the GA Cookie
// First, general and required hit data
$analytics->setProtocolVersion('1')
    ->setTrackingId('UA-26293624-12')
    ->setClientId('2133506694.1448249699')
    ->setUserId('123');

// Then, include the transaction data
$analytics->setTransactionId('7778922')
    ->setAffiliation('THE ICONIC')
    ->setRevenue(250.0)
    ->setTax(25.0)
    ->setShipping(15.0)
    ->setCouponCode('MY_COUPON');

// Include a product
$productData1 = [
    'sku' => 'AAAA-6666',
    'name' => 'Test Product 2',
    'brand' => 'Test Brand 2',
    'category' => 'Test Category 3/Test Category 4',
    'variant' => 'yellow',
    'price' => 50.00,
    'quantity' => 1,
    'coupon_code' => 'TEST 2',
    'position' => 2
];

$analytics->addProduct($productData1);

// You can include as many products as you need this way
$productData2 = [
    'sku' => 'AAAA-5555',
    'name' => 'Test Product',
    'brand' => 'Test Brand',
    'category' => 'Test Category 1/Test Category 2',
    'variant' => 'blue',
    'price' => 85.00,
    'quantity' => 2,
    'coupon_code' => 'TEST',
    'position' => 4
];

$analytics->addProduct($productData2);

// Don't forget to set the product action, in this case to PURCHASE
$analytics->setProductActionToPurchase();

// Finally, you must send a hit, in this case we send an Event
$analytics->setEventCategory('Checkout')
    ->setEventAction('Purchase')
    ->sendEvent();
```

### Batch Hits

[](#batch-hits)

GA has an endpoint that you can hit to register multiple hits at once, with a limit of 20 hits. Hits to be send can be placed in a queue as you build up the Analytics object.

Here's an example that sends two hits, and then empties the queue.

```
$analytics = new Analytics(false, false);

$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-xxxxxx-x')
    ->setClientId('xxxxxx.xxxxxx');

foreach(range(0, 19) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->sendEnqueuedHits(); //push 20 pageviews in a single request and empties the queue
```

The queue is emptied when the hits are sent, but it can also be empty manually with `emptyQueue` method.

```
$analytics = new Analytics(false, false);

$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-xxxxxx-x')
    ->setClientId('xxxxxx.xxxxxx');

foreach(range(0, 5) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->emptyQueue(); // empty queue, allows to enqueue 20 hits again

foreach(range(1, 20) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->sendEnqueuedHits(); //push 20 pageviews in a single request and empties the queue
```

If more than 20 hits are attempted to be enqueue, the library will throw a `EnqueueUrlsOverflowException`.

### Validating Hits

[](#validating-hits)

From Google Developer Guide:

> The Google Analytics Measurement Protocol does not return HTTP error codes, even if a Measurement Protocol hit is malformed or missing required parameters. To ensure that your hits are correctly formatted and contain all required parameters, you can test them against the validation server before deploying them to production.

To send a validation hit, turn on debug mode like this

```
// Make sure AsyncRequest is set to false (it defaults to false)
$response = $analytics
              ->setDebug(true)
              ->sendPageview();

$debugResponse = $response->getDebugResponse();

// The debug response is an associative array, you could use print_r to view its contents
print_r($debugResponse);
```

GA actually returns a JSON that is parsed into an associative array. Read ([here](https://developers.google.com/analytics/devguides/collection/protocol/v1/validating-hits)) to understand how to interpret response.

### Disable library hits for Staging/Dev environments

[](#disable-library-hits-for-stagingdev-environments)

In your app configuration, you can have a flag for enabling or disabling the library, this in order to not actually send hits to GA, in this case the lib returns a AnalyticsResponseInterface object that returns empty values.

This is specially useful in dev or staging environments.

```
// Instantiate the Analytics object by passing the second parameter in the constructor as TRUE
$analytics = new Analytics(true, true);
```

Contributors
------------

[](#contributors)

- Jorge A. Borges - Lead Developer ()
- Juan Falcón - [arcticfalcon](https://github.com/arcticfalcon)
- Syed Irfaq R. - [irazasyed](https://github.com/irazasyed)
- Andrei Baibaratsky - [baibaratsky](https://github.com/baibaratsky)
- Martín Palombo - [lombo](https://github.com/lombo)
- Amit Rana - [amit0rana](https://github.com/amit0rana)
- Stefan Zweifel - [stefanzweifel](https://github.com/stefanzweifel)
- Titouan Benoit - [nightbr](https://github.com/Nightbr)
- Hayashi Ryo - [ryo88c](https://github.com/ryo88c)
- Radek Hřebeček - [http://www.hrebecek.cz/](http://www.hrebecek.cz)
- edim24 - [ryo88c](https://github.com/edim24)
- venyii - [venyii](https://github.com/venyii)
- Peter Jaap Blaakmeer - [peterjaap](https://github.com/peterjaap)
- Alberto Bottarini - [alberto-bottarini](http://www.albertobottarini.com)

License
-------

[](#license)

THE ICONIC Google Analytics Measurement Protocol library for PHP is released under the MIT License.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 78.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~109 days

Recently: every ~276 days

Total

31

Last Release

972d ago

Major Versions

v0.1.1 → v1.0.02015-01-30

v1.1.5 → v2.0.02015-07-03

v1.x-dev → v2.1.02015-07-18

PHP version history (3 changes)v0.1.0PHP &gt;=5.4

v2.0.0PHP &gt;=5.5

v2.9.2PHP &gt;=7.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/647264f8dd71e5876f6edf224568bbe9b4d64511ab9a61f5b049f52184392176?d=identicon)[johnkarpn](/maintainers/johnkarpn)

---

Top Contributors

[![jorgeborges](https://avatars.githubusercontent.com/u/1531431?v=4)](https://github.com/jorgeborges "jorgeborges (280 commits)")[![8ctopus](https://avatars.githubusercontent.com/u/13252042?v=4)](https://github.com/8ctopus "8ctopus (39 commits)")[![Nightbr](https://avatars.githubusercontent.com/u/4228646?v=4)](https://github.com/Nightbr "Nightbr (4 commits)")[![stefanzweifel](https://avatars.githubusercontent.com/u/1080923?v=4)](https://github.com/stefanzweifel "stefanzweifel (4 commits)")[![alberto-bottarini](https://avatars.githubusercontent.com/u/1442934?v=4)](https://github.com/alberto-bottarini "alberto-bottarini (4 commits)")[![edim24](https://avatars.githubusercontent.com/u/6409091?v=4)](https://github.com/edim24 "edim24 (3 commits)")[![johnkarpn](https://avatars.githubusercontent.com/u/5538918?v=4)](https://github.com/johnkarpn "johnkarpn (3 commits)")[![jfalcondb](https://avatars.githubusercontent.com/u/11094411?v=4)](https://github.com/jfalcondb "jfalcondb (3 commits)")[![baibaratsky](https://avatars.githubusercontent.com/u/1774061?v=4)](https://github.com/baibaratsky "baibaratsky (3 commits)")[![rhrebecek](https://avatars.githubusercontent.com/u/1384186?v=4)](https://github.com/rhrebecek "rhrebecek (2 commits)")[![irazasyed](https://avatars.githubusercontent.com/u/1915268?v=4)](https://github.com/irazasyed "irazasyed (2 commits)")[![vntw](https://avatars.githubusercontent.com/u/502368?v=4)](https://github.com/vntw "vntw (1 commits)")[![goodjack](https://avatars.githubusercontent.com/u/1116129?v=4)](https://github.com/goodjack "goodjack (1 commits)")[![jonny-no1](https://avatars.githubusercontent.com/u/282458?v=4)](https://github.com/jonny-no1 "jonny-no1 (1 commits)")[![lombo](https://avatars.githubusercontent.com/u/495889?v=4)](https://github.com/lombo "lombo (1 commits)")[![morawskim](https://avatars.githubusercontent.com/u/1105278?v=4)](https://github.com/morawskim "morawskim (1 commits)")[![peterjaap](https://avatars.githubusercontent.com/u/431360?v=4)](https://github.com/peterjaap "peterjaap (1 commits)")[![rafaelmonteiro](https://avatars.githubusercontent.com/u/1180413?v=4)](https://github.com/rafaelmonteiro "rafaelmonteiro (1 commits)")[![ryo88c](https://avatars.githubusercontent.com/u/77841?v=4)](https://github.com/ryo88c "ryo88c (1 commits)")[![amit0rana](https://avatars.githubusercontent.com/u/236212?v=4)](https://github.com/amit0rana "amit0rana (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/johnkarpn-php-ga-measurement-protocol/health.svg)

```
[![Health](https://phpackages.com/badges/johnkarpn-php-ga-measurement-protocol/health.svg)](https://phpackages.com/packages/johnkarpn-php-ga-measurement-protocol)
```

###  Alternatives

[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3731.2M42](/packages/tencentcloud-tencentcloud-sdk-php)[convertkit/convertkitapi

Kit PHP SDK for the Kit API

2167.1k1](/packages/convertkit-convertkitapi)[mapado/rest-client-sdk

Rest Client SDK for hydra API

1125.9k2](/packages/mapado-rest-client-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
