Giter Club home page Giter Club logo

matomo-php-tracker's Introduction

PHP Client for Matomo Analytics Tracking API

The PHP Tracker Client provides all features of the Matomo Javascript Tracker, such as Ecommerce Tracking, Custom Variables, Event Tracking and more.

Documentation and examples

Check out our Matomo-PHP-Tracker developer documentation and Matomo Tracking API guide.

// Required variables
$matomoSiteId = 6;                  // Site ID
$matomoUrl = "https://example.tld"; // Your matomo URL
$matomoToken = "";                  // Your authentication token

// Optional variable
$matomoPageTitle = "";              // The title of the page

// Load object
require_once("MatomoTracker.php");

// Matomo object
$matomoTracker = new MatomoTracker((int)$matomoSiteId, $matomoUrl);

// Set authentication token
$matomoTracker->setTokenAuth($matomoToken);

// Track page view
$matomoTracker->doTrackPageView($matomoPageTitle);

Requirements:

  • JSON extension (json_decode, json_encode)
  • cURL or stream extension (to issue the HTTPS request to Matomo)

Installation

Composer

composer require matomo/matomo-php-tracker

Manually

Alternatively, you can download the files and require the Matomo tracker manually:

require_once("MatomoTracker.php");

License

Released under the BSD License

matomo-php-tracker's People

Contributors

bx80 avatar chris53897 avatar chris8934 avatar demichev avatar diosmosis avatar epnw-eric avatar exussum12 avatar findus23 avatar homerbond005 avatar igorrovenki avatar leighmarble avatar madman-81 avatar mattab avatar mzaman avatar olleharstedt avatar peter279k avatar rafiberlin avatar revoltek-daniel avatar rontu85 avatar sgiehl avatar shibby avatar silvershadowcc avatar tsteur avatar vmadmax avatar vpapaloukas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

matomo-php-tracker's Issues

How to handle possibility of blocking curl requests

Hi,
I'm a first time user of the piwik-php-tracker and I'm wondering how to integrate tracking in our project. I like to use it to trigger some events in the backend and send those to piwik so they can be viewed nicely in the piwik-UI. But I don't want to block the backend code with those calls. What if the piwik server does not answer? The default request-timeout is set to 600secs with a nice comment (https://github.com/piwik/piwik-php-tracker/blob/84a994a4d34a601a1b1da2c44a122807a1c4ad5b/PiwikTracker.php#L146). Maybe I'm wrong, but its sounds like a dangerous default. One can set the curl-timeout with ->setRequestTimeout() to a minimum of 1sec. But thats still a lot of time.
My question: is the piwik-php-tracker the right choice to track events out a complex webapp context? I could imagine to use pthreads (http://php.net/manual/de/book.pthreads.php) or overwriting the ->sendRequest() method to use CURLOPT_TIMEOUT_MS instead of CURLOPT_TIMEOUT to minimize the blocking. I'm not interested in the piwik-response atm.
How do you handle this in your projects?

disableCookieSupport() documentation clarification

I've also posted this question to the feedback button of the following page:
https://matomo.org/faq/general/faq_157/


Hey there!
I am using the matomo php API and I stumbled across the disableCookieSupport() function:
https://developer.matomo.org/api-reference/PHP-Matomo-Tracker#disablecookiesupport

Now to my observations this does not change anything, so I am wondering what this function will do. I wish that this gets more explained in the docs and optional here.

Also I've noticed that still 3 cookies are set:

  • _pk_cvar.1.ceca
  • _pk_id.1.ceca
  • _pk_ses.1.ceca

Now I am wondering what those cookies are used for. They are not listed above in the docs, so I guess the page is outdated? Also I am wondering if the disabling of the cookie really worked, it seems it did not? Could you please clarify this to me via email, but also in the docs.

Thanks a lot!

Creation of dynamic property MatomoTracker::$currentTs is deprecated

There are some deprecations in latest version of tracker:

Creation of dynamic property MatomoTracker::$currentTs is deprecated

Also other properties are affected:

  • MatomoTracker::$forcedVisitorId
  • MatomoTracker::$requestTimeout
  • MatomoTracker::$configCookiePath
  • MatomoTracker::$visitCount
  • MatomoTracker::$ecommerceLastOrderTimestamp
  • MatomoTracker::$doBulkRequests
  • MatomoTracker::$incomingTrackerCookies
        $this->currentTs = time();
        $this->createTs = $this->currentTs;
        $this->visitCount = 0;
        $this->currentVisitTs = false;
        $this->lastVisitTs = false;
        $this->ecommerceLastOrderTimestamp = false;

Why the tag @ignore for sendRequest()?

It would improve documentation to use full PHPDoc for that function, IMO. And instead of mixed, boolean|string can be used to clearly specify what is returned. I can make another PR for this if you like.

Add possibility to add custom tracking parameter

When a developer builds a plugin, say "Bandwidth", that defines a new tracking parameter, say "bw_bytes", then it is not possible to send this HTTP Tracking API parameter using the PHP Piwik Tracker. There should be the possibility to do this otherwise plugins that define a new dimension are not very useful.

It is to be defined whether we should reset those parameters after each sendRequest or not. Maybe we need both behavior

complete unit tests

As title. Currently no tests, there will be some after #77 is merged, but most of the code will be untested.

Packagist

Will be the packagist instalation method available shortly?

Curl Connection remaining open.

In line 1955 you are doing a curl_init, but you do not close the connection. I think you should do a curl_close($ch); on line 1986. Also, if the connection fails it will stop the entire script. It might be interesting to implement a retry for a set number of times so that it does not stop the importing of the entire set in the middle of the thing. I adapted the routine for myself in order to do 10 retries.

Create a new release

Hi there,

I'm working on solving matomo-org/matomo#6870, and to use composer well, this package would need to be versioned. The latest version packagist knows about is 1.0.0 (as defined by the Releases page).

If you could create a new release, we can make sure that the switch to managing PiwikTracker.php through composer doesn't downgrade the version of PiwikTracker.

Thanks!

Authentication failure

Just tried using the php tracker, but ran into an authentication failure when setting the visitor IP. The visit (with ua etc.) and title were logged, but with the web server IP.
As you can see I dumped $this after setting the auth token which showed the token and ip were properly set. They also appeared in the tracking url of the failure. I tried two auth tokens, one with super user access and one with site specific write access.

Tracking failures - Administration

Measurable
example.com (Id 4)

Problem
Request was not authenticated but authentication was required.

Solution
Set or correct a "token_auth" in your tracking request. Learn more

PHP code (from documentation example)

// Required variables
$matomoSiteId = 4;                  // Site ID
$matomoUrl = "https://example.com"; // Your matomo URL
$matomoToken = "";                  // Your authentication token

// Optional variable
$matomoPageTitle = self::$title;              // The title of the page

// Load object
require_once(__DIR__ . '/MatomoTracker.class.php');

// Matomo object
$mT = new MatomoTracker((int)$matomoSiteId, $matomoUrl);

// Set visitor IP
$mT->setIp(self::getIp());

// Set authentication token
print_r($mT->setTokenAuth($matomoToken));

// Track page view
$mT->doTrackPageView($matomoPageTitle);

Speedup Curl-Request with various Parameters

Hi, the curl request could work faster when added options like these:

CURLOPT_TCP_FASTOPEN => true // https://curl.se/libcurl/c/CURLOPT_TCP_FASTOPEN.html

CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4 // https://curl.se/libcurl/c/CURLOPT_IPRESOLVE.html -> shoud me maybe a setter method for peaple who wants to use ipv6

CURLOPT_ENCODING => '' // to enable compression, see php docs

CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS // see https://curl.se/libcurl/c/CURLOPT_HTTP_VERSION.html -> maybe as a setter too

Uncaught RuntimeException when Matomo host DNS couldn't resolve

Sometimes there's a problem with DNS and an address cannot be resolved. Then sadly, the tracker crashes out:

[11-Aug-2022 00:17:31 Europe/Berlin] PHP Fatal error: Uncaught RuntimeException: Could not resolve host: m.biblische-re
isen.de in /var/www/vhosts/biblische-reisen.de/biblical-tours.com/MatomoTracker.php:1761
Stack trace:
#0 /var/www/vhosts/biblische-reisen.de/biblical-tours.com/MatomoTracker.php(644): MatomoTracker->sendRequest()
#1 /var/www/vhosts/biblische-reisen.de/biblical-tours.com/config/analytics-body.php.inc(22): MatomoTracker->doTrackPageV
iew()
#2 /var/www/vhosts/biblische-reisen.de/biblical-tours.com/include/prototype/tail.php.inc(251): include('/var/www/vhosts.
..')
#3 /var/www/vhosts/biblische-reisen.de/biblical-tours.com/index.php(61): include('/var/www/vhosts...')
#4 {main}
thrown in /var/www/vhosts/biblische-reisen.de/biblical-tours.com/MatomoTracker.php on line 1761

The adress resolves normally except when there's a problem with connectivity to DNS-Servers. Would be great if this could be caught and maybe retried a couple of times.

Thanks for the great work, the tracker is just what I needed!

Notices

Heya,

i get a few notice errors

Notice: Undefined offset: 3 in vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 1296

Notice: Undefined offset: 4 in vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 1297

Get current visitors channel and campaign params

Hi!
Does the PHP Client for Matomo Analytics Tracking API provide a function to get Infos from current visitor profile like the channel (e.g. Google, Direct Call ...) and the campaign parameters? Maybe after getting the visitors id. Therefore I found the function getVisitorId().

I would be very happy about any help or a hint!

Greetings,
Christiana

PHP 7.4: Trying to access array offset on value of type null

When calling something like the following to track without Javascript:

PiwikTracker::$URL = 'https://mypage.com/matomo';
$tracker = new \PiwikTracker(1, 'https://mypage.com/matomo');

I'm seeing the following errors:

NOTICE: Trying to access array offset on value of type null in [...]/matomo/vendor/piwik/piwik-php-tracker/PiwikTracker.php on 1815
NOTICE: Trying to access array offset on value of type null in [...]/matomo/vendor/piwik/piwik-php-tracker/PiwikTracker.php on 1818

PHP v7.4.1
Matomo v3.13.1-b1

Goals attribution only show 'direct' attribution

Hi!

We've been asked to submit an issue here by the Matomo support team.

We use Matomo Cloud for analytics and to track goal conversions (subscription purchases). We experience that our goals only get 'direct' attribution. See the attached files that show our code.

Here's how a signup/conversion takes place
• A user lands on Onlime.dk via an affiliate (Wordpress)
• The user creates a free account on Onlime.dk (Wordpress)
• The user logs into onlime.dk/user/login and purchases a subscription (Webapp)
• We have set up goals to each subscription purchase, so we should see an entry attribute of ‘Websites’ instead of ‘Direct’.

Attachment
Onlime matomo tracking script 1 (Wordpress)
Onlime matomo tracking script 2 (webapp)
Code to track free subscriptions
Code to track paid subsciptions

PHP 8.2: Creation of dynamic property NNN is deprecated

I'm using MatomoTracker in a PHP application running on various PHP Versions (7.4, 8.0, 8.1, 8.2). While most of the versions are running just fine on PHP 8.2 I see a lot of deprecation Messages when using the Tracker:

PHP Deprecated:  Creation of dynamic property MatomoTracker::$ecommerceItems is deprecated in APPLICATION/vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 85
PHP Deprecated:  Creation of dynamic property MatomoTracker::$attributionInfo is deprecated in APPLICATION/vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 86
PHP Deprecated:  Creation of dynamic property MatomoTracker::$eventCustomVar is deprecated in APPLICATION/vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 87
PHP Deprecated:  Creation of dynamic property MatomoTracker::$forcedDatetime is deprecated in APPLICATION/vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 88
PHP Deprecated:  Creation of dynamic property MatomoTracker::$forcedNewVisit is deprecated in APPLICATION/vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 89
PHP Deprecated:  Creation of dynamic property MatomoTracker::$networkTime is deprecated in APPLICATION/vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 90
PHP Deprecated:  Creation of dynamic property MatomoTracker::$serverTime is deprecated in APPLICATION/vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 91

implement the fluent interface

The function addEcommerceItem() has no return value.

Due to your documentation this function should be called before e.g. doTrackEcommerceOrder() is called.
If you do so you will get

Fatal error: Call to a member function doTrackEcommerceOrder() on null

In our opinion you should implement the fluent interface and return the object instance:

689 = $this->ecommerceItems[] = array($sku, $name, $category, $price, $quantity);
690 + return $this;

Thanks in advance for feedback!
Have a great time!

Example on Matomo website has incorrect API usage

Unsure if this is the proper place to report it. But I couldn't find a issue manager for the website. On this page the example for 'Method 2: HTTP Request' wrongly uses MatomoTracker() instead of PiwikTracker(). This will cause the script to fail. While this may be subject to be renamed down the road as of now PiwikTracker() is still the correct usage with the current available version of the PHP tracker.

new release

Can we have a release? I still maintain my fork for my organization and I would like to require the current repo instead of my fork.

No tracking since 1st of October

Since the first of October, (maybe a bit earlier), my PHP/server-side tracking entirely stopped working. Nothing is tracked anymore.

Javascript etc. is still working, but not ideal for some situations.

PSR-7 support

Are there any plans for PSR-7 support? It would be great if we could set up tracking and then get a PSR-7 request from the tracker to send it out using our own HTTP client. Also creating a new tracker from a PSR-7 server request would be appreciated. If you're open for this I gladly make both PR's

Licence Mismatch

Composer suggests BSD-2-Clause

Licence File suggests 3 Clause, could one of them be updated so they match please ?

Namespace branch and namespace

Can someone add a branch, either:

  • A legacy branch on the assumption that we're using master for namespaced refactoring (or)
  • A develop/namespace branch on the assumption that master will remain the legacy branch

Obviously, the next step is to actually add a namespace. If someone is allowed to make an executive decision on that namespace (and class name), please do so and commit it. Otherwise, what's the process for making such a decision. As a starting point, a step in the right direction is:

Namespace: Piwik
ClassName: PhpTracker

I've also patched together the beginnings of a zf2 tracking module. I was learning ZF2 in parallel so it needs some work, but I would be willing to contribute it to Piwik (under a new name and more permissive license) if there was any interest in heading this direction.

Not possible to create multiple Piwik tracker instances having different API urls

Because $URL is a constant and not a property of the class: https://github.com/piwik/piwik-php-tracker/blob/1.0.0/PiwikTracker.php#L32

$tracker1 = new \PiwikTracker(1, 'http://demo.piwik.org/piwik.php');
$tracker2 = new \PiwikTracker(1, 'http://apache.piwik/piwik.php');

Both tracker instances will use http://apache.piwik/piwik.php as URL.

Use case see matomo-org/matomo#4589 where up to 3 trackers can be configured and we need to send the same data to different trackers.

More virtualization of MatomoTracker class

Summary

May I ask not popular but small feature? We are using MatomoTracker class to emulate user page visits when payment callback is executed. MatomoTracker is poorly virtualized so I overrode the whole sendRequest() method just to replace proxy (getProxy() method is private), add CURLOPT_HTTPHEADER to curl and ['http']['header'] to $stream_options.
It works but each time Matomo is updated I compare code, make changes, etc.
Can you make getProxy() protected and add empty protected methods for curl options/stream_options?

Your Environment

  • Matomo Version: 4.7.1

How to know if site ID or auth token are incorrect

I have been testing this SDK and in general it works well. However, I haven't found a way to tell if incorrect values were set for the site ID or auth token, as the response to $tracker->doTrackPageView(...) is always the same.

I have noticed the visit is not tracked by the server if any of those values is wrong (let's say you have a typo n the auth token, or the site ID is not known by Matomo server), but the method does not throw any exception or return a different result, so it could pass unnoticed for some time.

Add methods for custom dimensions

With matomo-org/matomo#11524 it will be good to actually provide methods for setting and removing custom dimensions instead of having to use setCustomTrackingParameter(). We would need to see whether we reset them after the next request and whether we also allow passing custom dimensions with doTrackPageview, doTrackEvent etc similar to the JS tracker. We need to make sure to have consistent behaviour with JS tracker and if possible with current custom variables behaviour (if it makes sense)

Current time added twice in method deleteCookies()

$this->currentTs is added twice upon calling method deleteCookies()

Once at line 3 in

  public function deleteCookies()
  {
    $expire = $this->currentTs - 86400;
    $cookies = array('id', 'ses', 'cvar', 'ref');
    foreach($cookies as $cookie) {
      $this->setCookie($cookie, '', $expire);
    }
  }

and once at line 3 in

  protected function setCookie($cookieName, $cookieValue, $cookieTTL)
  {
    $cookieExpire = $this->currentTs + $cookieTTL;
    if(!headers_sent()) {
    setcookie($this->getCookieName($cookieName), $cookieValue, $cookieExpire, $this->configCookiePath, $this->configCookieDomain);
    }
  }

This results in cookies having expiration dates set to year 2060.

PHP Deprecation warning when running tracker on PHP 8.1

While running the API tests for one of the plugins I received a bunch of the following PHP warning:

PHP Deprecated:  urlencode(): Passing null to parameter #1 ($string) of type string is deprecated in matomo/vendor/matomo/matomo-php-tracker/MatomoTracker.php on line 1931

The warnings appear to be happening because a line of the tracker is trying to encode the referrer URL when there isn't one.

PHP: 8.1.2
Matomo: 4.12.3
MultiChannelConversionAttribution: 4.1.0

Composer: Ambiguous class resolution, "PiwikTracker" was found in both..

Composer issues the warning below when generating optimized autoload files:

Warning: Ambiguous class resolution, "PiwikTracker" was found in both "C:\project\vendor/matomo/matomo-php-tracker/.\MatomoTracker.php" and "C:\project\vendor/matomo/matomo-php-tracker/.\PiwikTracker.p
hp", the first will be used.

The solution would be to remove the class declaration from MatomoTracker.php since this included in PiwikTracker.php.

Support new `ca` tracking parameter for tracking requests that aren't page views

See matomo-org/matomo#16569 to learn more about the problem it fixes and visit https://developer.matomo.org/api-reference/tracking-api for more documentation about the new ca parameter.

Basically, we should be sending &ca=1 along any tracking request that isn't a page view. Practically, we should for now only send &ca=1 along any event and content tracking requests.

The parameter isn't required but it helps for more accurate tracking for edge cases where a user suddenly disables eg an event, goal or ecommerce plugin but still keeps sending these requests. If the parameter is not sent, Matomo would turn the tracking request into a page view and track a page view even though the tracking request should be ignored.

Let me know if there are any questions about this.

Documentation? Example? How to use?

First, I thank you very much for the awesome matomo tracking software! I'm using it for many years now. Sadly I'm now very disappointed of the current version of this php tracking library :(
I can't find any example, or any installation instructions.
I used your php library for many years now and suddenly it was broken!
Today I tried to update and I was very happy to see you published your library as composer installable.

Please give me a code sample with a basic example that shows how to track with the token auth.

BTW: The reason everything broke is an authentication error.

disableSendImageResponse() does not work properly

https://developer.matomo.org/api-reference/PHP-Matomo-Tracker#disablesendimageresponse

I am using the following code:

$matomoTracker->disableSendImageResponse();
$ret = $matomoTracker->getUrlTrackPageView($page->title());

When I open the url at $ret I always see a gif image instead of a 204 response.

Also, is there an option to tell matomo if the url got requested, the user uses a screen resolution of AxB? Combined with some clever css we could track the resolution of user devices:
https://medium.com/javascript-in-plain-english/tracking-with-css-ec98e3d81046
https://www.templarbit.com/blog/2018/03/20/tracking-users-with-css/

Owner of this project?

Hello,

Would it be possible for the owner of this project to take a look at my pull request please?

#122

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.