How to use Matomo's Server Side Tracking

How to use Matomo's Server Side Tracking

Published at: 08/26/2022
Updated at: 08/29/2022
Categories
Tags

Use Server Side Tracking on Matomo to enhance your analytics

With Matomo we can enable the server side analytics tracking and get a more precise and enhanced monitoring of your website's traffic.

Server-Side Tracking vs Client-Side Tracking: in short

To explain it in a few words, client side tracking works on the user's browser and is generally made using Javascript. The advantage is that it is kinda easy to collect some metrics and also lightweight on the server.

On the other hand, server side tracking doesn't use Javascript and is executed directly by the server itself. We might use PHP to analyze the requests we receive from our users.

There are also Log Analytics softwares like Awstats or GoAccess, which will analyze the server's log files to determine the views of the users on our web pages.

The main advantage of server side tracking and log analysis is that we can even monitor users that are making use of AdBlock or similar systems, which prevent the Javascript tracking code from working correctly.

How to setup server-side tracking with Matomo

Actually using server side analytics tracking with Matomo is pretty easy.

We will use the PHP Library as an example, because it is one of the most used languages when making websites.

  1. Download MatomoTracker.php and PiwikTracker.php from Github or any other server side tracking library
  2. Upload the MatomoTracker.php and PiwikTracker.php files in your web server, it might be in the folder /public_html/matomo/, using Filezilla or any other FTP software
  3. In our web application, we add the following PHP Code on all our pages, or in the template, based on what kind of tool we are using
# File template.php or similar, make sure this code is loaded in every page
$matomoSiteId = 1;
$matomoUrl = '{url-to-matomo-platform}';
$matomoToken = '{inser-auth-token-here}';
$matomoPageTitle = '';

require_once '{path-to-file}/MatomoTracker.php';

try {
    $matomoTracker = new MatomoTracker($matomoSiteId, $matomoUrl);
    $matomoTracker->setRequestTimeout(2);
    $matomoTracker->setTokenAuth($matomoToken);
} catch (Exception $e) {
}

# File page.php, to customize the page title for Matomo
if (!empty($matomoTracker)) {
    $matomoTracker->doTrackPageView($matomoPageTitle);
}

Let's see some more details:

  • $matomoSiteId is the id of the website configured on Matomo, you can find it in the Settings by going to Settings > Websites > Manage
  • $matomoUrl is the public url used by Matomo, e.g. https://matomo.yourwebsite.com
  • $matomoToken is a unique random code that needs to be configured (see the paragraph Configure the Auth Token)
  • $matomoPageTitle is the title of the page to send to Matomo, if you are using a CMS or Framework you will need to find a way to configure this variable properly, while if you are using single PHP files for every page you can add it in every file
  • require_once will load the MatomoTracker.php file, replace {path-to-file} with the actual path to get MatomoTracker.php, an example could be /var/www/html/website.com/vendor/matomo/MatomoTracker.php
  • $matomoTracker will contain the MatomoTracker class with its own properties and methods
  • setRequestTimeout is used to give a maximum time to send a request to our Matomo: otherwise, if your Matomo server is not working, the page will be slowed down heavily
  • setTokenAuth will set the Authorization Token for Matomo
  • doTrackPageView is the function that sends the PageView evento to Matomo, it works the same way as in the Javascript code. It is mandatory to give this function a string to use as page title, it will then be used by Matomo in the visits report
  • the try/catch block and the if at the end are useful to prevent triggering PHP's Fatal Errors in case our Matomo istance is not responding

Configure the Auth Token

To configure the Auth Token in PHP, go in Matomo's Settings at the menu Settings > Personal > Security and at the bottom you will find Auth Tokens, press on Create new token.

Create a new Auth Token on Matomo
Create a new Auth Token on Matomo

You will need to enter your administrator password again, then you will be asked to give a description and generate the token. A random string will appear, and you might receive a security notification by email.

Insert a description to generate your token
Insert a description to generate your token

Token example: 2a96a7df4c6f09272bf445d1c753d4a8 (each token is unique)

Matomo Auth Token has been generated
Matomo Auth Token has been generated

After inserting the token into the PHP code we can test that the tracking is working as intended, by viewing the public website and verifying that the session is being registered by Matomo.

Can I use both Javascript and Server Side Tracking?

Yes, you will need to remove or comment the Javascript line that sends the PageView event to Matomo, otherwise you will find doubled views. I have tested this possibility and it can really happen to have duplicated visits if you use the pageview tracking both with Javascript and PHP.

Code sample:

var _paq = window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['enableHeartBeatTimer', 15]);
// The following line has been remove to avoid duplicated views
// _paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
    var u = "https://matomo.yourwebsite.com/";
    _paq.push(['setTrackerUrl', u + 'matomo.php']);
    _paq.push(['setSiteId', '1']);
    var d = document,
        g = d.createElement('script'),
        s = d.getElementsByTagName('script')[0];
    g.type = 'text/javascript';
    g.async = true;
    g.src = u + 'matomo.js';
    s.parentNode.insertBefore(g, s);
})();

You will see I have also used enableHeartBeatTimer, it is a function that allows to more accurately track the time spent by a user on the page, by sending a ping request to Matomo every N seconds (minimum 15). Also have a look at the Javascript documentation for Matomo.

You can also configure Event tracking on Matomo, like when you want to know which links are being clicked by your users.

Please be aware that some tracking modes will be blocked by the Do Not Track functionality in Firefox and other browsers, or by Ad blocking tools.

AdBlocker and Do Not Track

Most of the AdBlockers (AdBlock, uBlock and similar) will block the tracking initialized by Matomo. As an example, the word "matomo" might be banned, so any resource like matomo.js or matomo.php will not be loaded.

At the same time, the Do Not Track mode from Firefox will block some kinds of trackers, if the user's browser is using it and if the server does use the relative Header.

I have tested both these cases and they can be resolved with the server side tracking. Still, using Javascript to track some actions or events will be blocked anyway. You might want to configure your events tracking on the server side, but this will require more work.

You might build your links with a unique php file called link.php and this will take care to redirect the user to the correct page. Before doing so, it might send an event to Matomo in PHP. The main problem of this approach is that it will clearly make link and resources management harder, and it will require more data-entry from you.

Privacy concerns

Tracking those who do not wish to be tracked is a bad idea, but we don't necessarily need to give up on monitoring our views.

We surely need to do our best to respect a user's privacy. If we collect only aggregated data for statistical purposes, there will be no problems, but in case we want to perform remarketing and profilation, we will need to require the explicit consent to the user, and activate the tracking only after receiving it.

As an example, we might configure a PHP page to require consent and set a technical cookie if given.

After that we will verify that the cookie has been set and, in that case, we start tracking:

if (!empty($_COOKIE['matomoTrackingConsent'])) {
    # File template.php or similar, make sure this code is loaded in every page
    $matomoSiteId = 1;
    $matomoUrl = 'https://matomo.yourwebsite.com';
    $matomoToken = '2a96a7df4c6f09272bf445d1c753d4a8 ';
    $matomoPageTitle = 'Page title';

    require_once '/var/www/html/yourwebsite/vendor/matomo/MatomoTracker.php';

    try {
        $matomoTracker = new MatomoTracker($matomoSiteId, $matomoUrl);
        $matomoTracker->setRequestTimeout(2);
        $matomoTracker->setTokenAuth($matomoToken);
    } catch (Exception $e) {
    }

    # File page.php, to customize the page title for Matomo
    if (!empty($matomoTracker)) {
        $matomoTracker->doTrackPageView($matomoPageTitle);
    }
}

Of course by doing so we might lose the first access, because we cannot activate the tracking before the user has given consent to do so.

Conclusions

Now your Matomo Server Side Tracking is set up!

If you liked this article, follow me on Facebook and subscribe our Youtube channel! If you need support write me in chat or by email!

Leave a comment

All comments will be subject to approval after being sent. They might be published after several hours.

You can just use a random nickname, it is usefull to allow me to at least answer your comments. And if you choose to submit your email, you can receive a notification whenever I reply to your comment.

*
  • 2023-08-16 14:55:06

    Author: eartahhj

    @Csti you should check in your PHP/Nginx/Apache logs to see what the error for the crash is. Potentially, it could be for PHP memory limit, in that case, go to your php.ini or webserver settings and try increasing the limit. For example, if you have 64M, try increasing to 128M or 256M. Ideally, you rarely need more than 512M even for bigger websites, because the maximum memory will be used per-script, and not "in total". Other issues could be because you are using a version of PHP which is not supported by the script or viceversa, for example if the script is using a PHP8 feature but your server is running PHP7. Other reasons could regard the database, but that's less likely.

  • 2023-08-16 13:46:43

    Author: Csti

    @eartahhj thanks for the clarification. I decided to go with your set-up. Had to do a backup for my website and re-install Matomo. I run into some problems with adding the script. When I add this to template.php the site crashes completely. I then put it into template-loader.php but no cookies are tracked, so it does not even load. Before my backup I put this into the index.php directly, however after a few times the design seems to crash and it gets cropped left and right. Do you have an idea what to do about this, specifically why the website crashes when putting into template.php? Thanks in advance

  • 2023-07-10 09:34:41

    Author: eartahhj

    @Csti to do a server 2 server tracking, you want to use the PHP Tracker. You can still use matomo.js if you are going to use the Matomo Javascript API to start tracking the user. You can also disable the cookies in Javascript, read here: https://matomo.org/faq/general/faq_157/ - and more info about cookieless tracking can be found also here: https://matomo.org/faq/new-to-piwik/is-there-a-cookie-less-alternative-to-google-analytics/ - Finally, I think your best solution could be the Log Analytics: read here https://matomo.org/log-analytics/ and here: https://matomo.org/guide/tracking-data/import-server-logs/ - your server needs to have Python tho.

  • 2023-07-10 09:27:27

    Author: Csti

    @eartahhj, and if I only wanted to do server 2 server tracking, do I even need the matomo.js file (as it says client tracking)?

  • 2023-07-10 09:01:43

    Author: eartahhj

    @Csti oh well, but that's a completely different thing then. It is called Cookieless tracking and you can read about it here: https://matomo.org/cookie-consent-banners/ - and also read about the visitor config_id: https://matomo.org/faq/general/how-is-the-visitor-config_id-processed/ - Usually cookies are the easier way to track users across pages. I have not tried cookieless tracking yet, so I am not 100% sure about how it works.

  • 2023-07-10 08:54:49

    Author: Csti

    @eartahhj, I do not use the javascript at all. I wanted to setup up a server2server tracking variant without using any cookies, so I do not have to ask user for a consent. From my understanding this is the "new" GDPR compliant possibility. If I delete the cookies in matomo.php and matomo.js is the tracking then still possible in the background?

  • 2023-07-07 14:35:20

    Author: eartahhj

    @Csti are you using both tracking methods, PHP and Javascript? They both might set cookies. Try removing the Javascript code from the page, delete your cookies, reload the page, and see if the cookies still appear. If they do, it's probably the PHP tracker. Having a cookie is a not a problem tho, as long as you use them only for statistical purposes. When the user declines consent, you might want to delete the cookies related to Matomo, both in the Javascript tracker and PHP tracker. Take a look at the Javascript API, you might want to use something like deleteCookies(). https://developer.matomo.org/api-reference/tracking-javascript#managing-consent

  • 2023-07-07 11:45:28

    Author: Csti

    @eartahhj, yes I chose the cookieless method specifically. I do not understand now I am seeing the cookies pk_ses, pk_cvar, pk_id. again in the browser. How does Matomo set the cookies if I do not use the tracking code? Is this triggered through the Matomo.js file? Do you know how to deactivate it, so I do not see any cookies?

  • 2023-07-07 07:19:05

    Author: eartahhj

    @Jason thank you for giving your feedback.

  • 2023-07-07 07:18:51

    Author: eartahhj

    @Csti all right but remember you can have both the PHP and Javascript tracking running at the same time, just comment the trackPageView event in the Javascript one to avoid having double hits. Having both enabled is useful for accuracy, but of course you can use only the server side one if you prefer.

  • 2023-07-07 04:09:32

    Author: Jason

    I had the same error 'Operation timed out after 2000 milliseconds with 0 out of -1 bytes received With this I cannot access any of Matomo other features.' because I was missing the ending / off my matomo instance url lol

  • 2023-07-06 14:42:49

    Author: Csti

    @eartahhj, never mind my last comment! There was in issue with a file. I also explicitely blocked all cookies in Matomo. Now at least I cannot find any cookies.

  • 2023-07-06 14:27:38

    Author: Csti

    @eartahhj, thanks for the information! As for the server side tracking I have checked again and now suddenly these cookies appear: pk_ses, pk_cvar, pk_id. I thought that these will be ignored. However it looks like as this stands in the matomo.js file and is being triggered. In Matomo I only set up my website as a measurable without implementing the javascript code..

  • 2023-07-05 20:25:14

    Author: eartahhj

    @Csti actually I do not use any plugin for that, I know there are many like Iubenda, Cookiebot, Cookiehub etc, but they all work on the client-side. On a Laravel and on a CodeIgniter project I made, which are gameadvisor.net and swiccy.it, I have made it so that if the user does not accept some cookies, the consent will be blocked. Of course there can be issues and differences between blocking server side and client side. If you want something easier, you can use a Javascript solution and then eventually use their API (for example, from Cookiebot) to start or do not start the Matomo tracking. As for the PHP Tracker itself of course, you will have to block that server side. You could still use a Javascript plugin and then use the php function setcookie() to set a cookie that says the user has refused tracking. On the next page load, your PHP tracking can be disabled if the cookie is set. Actually, you should go for the opt-out and not opt-in, so by default your PHP tracker should be off, and then turn it on only if the user accepted tracking. But in general, remember that Matomo is GDPR compliant and, unless you need really heavy tracking, you can track users even without their consent, if it is only for statistical purposes. You can have a look at Github to see how I implemented a Cookie Banner with Laravel: https://github.com/search?q=repo%3Aeartahhj%2FGameAdvisor%20showCookiePolicyBanner&type=code

  • 2023-07-05 15:40:55

    Author: Csti

    Hi @eartahhj, thanks for the info. I've checked all requirements. Finally I figured the problem with a system check. The files were not uploaded via FTP in binary mode, but directly on Plesk. This caused an error in the file length. Now it works great! Really nice. I do have another question about consent management - in your script at the end where you add the clause about asking for consent - what consent plugin do you use / can you recommend to connect this too?

  • 2023-07-03 16:47:44

    Author: eartahhj

    @Csti this is really weird, could it be linked to CURL? Do you have CURL enabled in your PHP? Also I would advise checking you meet all the requirements for Matomo: https://matomo.org/faq/on-premise/matomo-requirements/ You can also trying increasing the PHP execution time but it still seems weird to me. What version of PHP are you running? I would recommend using 8.1 at least.

  • 2023-07-03 09:05:14

    Author: Csti

    Hi eartahhj, thanks, I have checked the paths and the messages and could fix the problem. However now I get this: Operation timed out after 2000 milliseconds with 0 out of -1 bytes received With this I cannot access any of Matomo other features. Do you know how to fix this error?

  • 2023-07-01 19:50:07

    Author: eartahhj

    @Csti hello, could it be the DOCUMENT_ROOT of your website? It seems like PHP is looking to include the file from the wrong folder (note the /domaincom/ instead of /2.domain.com/ that is used after). Or maybe you are using a wrong path in the include/require php function?

  • 2023-07-01 19:25:09

    Author: Csti

    Hello, thanks for the article. I was following your instructions. I've done all the steps but seem to get an error with loading the MatomoTracker.php in Matomo. I'm using Plesk as web server. I have checked the link to the file several times and don't see any mistake. Do you have an idea what the error message suggests here - (I've replaced my domain with "domain.com". Matomo was installed on a subdomain 2.domain.com in this example) Error: Failed opening required: '/var/www/domaincom/vendor/matomo/matomo-php-tracker/MatomoTracker.php' (include_path='/var/www/vhosts/domain.com/2.domain.com/vendor/pear/pear_exception:/var/www/vhosts/domain.com/2.domain.com/vendor/pear/console_getopt:/var/www/vhosts/domain.com/2.domain.com/vendor/pear/pear-core-minimal/src:/var/www/vhosts/domain.com/2.domain.com/vendor/pear/archive_tar:.:/opt/plesk/php/8.1/share/pear Appreciate your help.