MatomoTracker implements the Matomo Tracking Web API.
For more information, see: https://github.com/matomo-org/matomo-php-tracker/
This class defines the following properties:
$URL
— Matomo base URL, for example http://example.org/matomo/ Must be set before using the class by calling MatomoTracker::$URL = 'http://yourwebsite.org/matomo/';$DEBUG_APPEND_URL
$ecommerceItems
$attributionInfo
$eventCustomVar
$forcedDatetime
$forcedNewVisit
$networkTime
$serverTime
$transferTime
$domProcessingTime
$domCompletionTime
$onLoadTime
$pageCustomVar
$ecommerceView
$customParameters
$customDimensions
$customData
$hasCookies
$token_auth
$userAgent
$country
$region
$city
$lat
$long
$width
$height
$plugins
$localHour
$localMinute
$localSecond
$idPageview
$idPageviewSetManually
$idSite
$urlReferrer
$pageCharset
$pageUrl
$ip
$acceptLanguage
$clientHints
$configVisitorCookieTimeout
$configSessionCookieTimeout
$configReferralCookieTimeout
$userId
$forcedVisitorId
$cookieVisitorId
$randomVisitorId
$configCookiesDisabled
$configCookiePath
$configCookieDomain
$configCookieSameSite
$configCookieSecure
$configCookieHTTPOnly
$currentTs
$createTs
$requestTimeout
$requestConnectTimeout
$doBulkRequests
$storedTrackingActions
$sendImageResponse
$outgoingTrackerCookies
$incomingTrackerCookies
$visitorCustomVar
$DEBUG_LAST_REQUESTED_URL
— Used in tests to output useful error messages.$URL
Matomo base URL, for example http://example.org/matomo/ Must be set before using the class by calling MatomoTracker::$URL = 'http://yourwebsite.org/matomo/';
string
value.$DEBUG_APPEND_URL
$ecommerceItems
$attributionInfo
$eventCustomVar
$forcedDatetime
$forcedNewVisit
$networkTime
$serverTime
$transferTime
$domProcessingTime
$domCompletionTime
$onLoadTime
$pageCustomVar
$ecommerceView
$customParameters
$customDimensions
$customData
$hasCookies
$token_auth
$userAgent
$country
$region
$city
$lat
$long
$width
$height
$plugins
$localHour
$localMinute
$localSecond
$idPageview
$idPageviewSetManually
$idSite
$urlReferrer
$pageCharset
$pageUrl
$ip
$acceptLanguage
$clientHints
$configVisitorCookieTimeout
$configSessionCookieTimeout
$configReferralCookieTimeout
$userId
$forcedVisitorId
$cookieVisitorId
$randomVisitorId
$configCookiesDisabled
$configCookiePath
$configCookieDomain
$configCookieSameSite
$configCookieSecure
$configCookieHTTPOnly
$currentTs
$createTs
$requestTimeout
$requestConnectTimeout
$doBulkRequests
$storedTrackingActions
$sendImageResponse
$outgoingTrackerCookies
$incomingTrackerCookies
$visitorCustomVar
$DEBUG_LAST_REQUESTED_URL
Used in tests to output useful error messages.
The class defines the following methods:
__construct()
— Builds a MatomoTracker object, used to track visits, pages and Goal conversions for a specific website, by using the Matomo Tracking API.setApiUrl()
setPageCharset()
— By default, Matomo expects utf-8 encoded values, for example for the page URL parameter values, Page Title, etc.setUrl()
— Sets the current URL being trackedsetUrlReferrer()
— Sets the URL referrer used to track Referrers details for new visits.setGenerationTime()
— This method is deprecated and does nothing.setPerformanceTimings()
— Sets timings for various browser performance metrics.clearPerformanceTimings()
— Clear / reset all previously set performance metrics.setAttributionInfo()
— Sets the attribution information to the visit, so that subsequent Goal conversions are properly attributed to the right Referrer URL, timestamp, Campaign Name & Keyword.setCustomVariable()
— Sets Visit Custom Variable.getCustomVariable()
— Returns the currently assigned Custom Variable.clearCustomVariables()
— Clears any Custom Variable that may be have been set.setCustomDimension()
— Sets a specific custom dimensionclearCustomDimensions()
— Clears all previously set custom dimensionsgetCustomDimension()
— Returns the value of the custom dimension with the given idsetCustomTrackingParameter()
— Sets a custom tracking parameter.clearCustomTrackingParameters()
— Clear / reset all previously set custom tracking parameters.setNewVisitorId()
— Sets the current visitor ID to a random new one.setIdSite()
— Sets the current site ID.setBrowserLanguage()
— Sets the Browser language.setUserAgent()
— Sets the user agent, used to detect OS and browser.setClientHints()
— Sets the client hints, used to detect OS and browser.setCountry()
— Sets the country of the visitor.setRegion()
— Sets the region of the visitor.setCity()
— Sets the city of the visitor.setLatitude()
— Sets the latitude of the visitor.setLongitude()
— Sets the longitude of the visitor.enableBulkTracking()
— Enables the bulk request feature.disableBulkTracking()
— Disables the bulk request feature.enableCookies()
— Enable Cookie Creation - this will cause a first party VisitorId cookie to be set when the VisitorId is set or resetdisableSendImageResponse()
— If image response is disabled Matomo will respond with a HTTP 204 header instead of responding with a gif.doTrackPageView()
— Tracks a page viewsetPageviewId()
— Override PageView id for every use of doTrackPageView()
.getPageviewId()
— Returns the PageView id.doTrackEvent()
— Tracks an eventdoTrackContentImpression()
— Tracks a content impressiondoTrackContentInteraction()
— Tracks a content interaction.doTrackSiteSearch()
— Tracks an internal Site Search query, and optionally tracks the Search Category, and Search results Count.doTrackGoal()
— Records a Goal conversiondoTrackAction()
— Tracks a download or outlinkaddEcommerceItem()
— Adds an item in the Ecommerce order.doTrackEcommerceCartUpdate()
— Tracks a Cart Update (add item, remove item, update item).doBulkTrack()
— Sends all stored tracking actions at once.doTrackEcommerceOrder()
— Tracks an Ecommerce order.doTrackPhpThrowable()
— Tracks a PHP Throwable a crash (requires CrashAnalytics to be enabled in the target Matomo)doTrackCrash()
— Track a crash (requires CrashAnalytics to be enabled in the target Matomo)doPing()
— Sends a ping request.setEcommerceView()
— Sets the current page view as an item (product) page view, or an Ecommerce Category page view.getUrlTrackPageView()
— Builds URL to track a page view.getUrlTrackEvent()
— Builds URL to track a custom event.getUrlTrackContentImpression()
— Builds URL to track a content impression.getUrlTrackContentInteraction()
— Builds URL to track a content interaction.getUrlTrackSiteSearch()
— Builds URL to track a site search.getUrlTrackGoal()
— Builds URL to track a goal with idGoal and revenue.getUrlTrackAction()
— Builds URL to track a new action.getUrlTrackCrash()
— Builds URL to track a crash.setForceVisitDateTime()
— Overrides server date and time for the tracking requests.setForceNewVisit()
— Forces Matomo to create a new visit for the tracking request.setIp()
— Overrides IP addresssetUserId()
— Force the action to be recorded for a specific User.getUserIdHashed()
— Hash function used internally by Matomo to hash a User ID into the Visitor ID.setVisitorId()
— Forces the requests to be recorded for the specified Visitor ID.getVisitorId()
— If the user initiating the request has the Matomo first party cookie, this function will try and return the ID parsed from this first party cookie (found in $_COOKIE).getUserAgent()
— Returns the currently set user agent.getIp()
— Returns the currently set IP address.getUserId()
— Returns the User ID string, which may have been set via: $v->setUserId('username@example.org');deleteCookies()
— Deletes all first party cookies from the clientgetAttributionInfo()
— Returns the currently assigned Attribution Information stored in a first party cookie.setTokenAuth()
— Some Tracking API functionality requires express authentication, using either the Super User token_auth, or a user with 'admin' access to the website.setLocalTime()
— Sets local visitor timesetResolution()
— Sets user resolution width and height.setBrowserHasCookies()
ash; Sets if the browser supports cookies This is reported in "List of plugins" report in Matomo.setDebugStringAppend()
— Will append a custom string at the end of the Tracking request.setPlugins()
— Sets visitor browser supported pluginsdisableCookieSupport()
— By default, MatomoTracker will read first party cookies from the request and write updated cookies in the response (using setrawcookie).getRequestTimeout()
— Returns the maximum number of seconds the tracker will spend waiting for a response from Matomo.setRequestTimeout()
— Sets the maximum number of seconds that the tracker will spend waiting for a response from Matomo.getRequestConnectTimeout()
— Returns the maximum number of seconds the tracker will spend trying to connect to Matomo.setRequestConnectTimeout()
— Sets the maximum number of seconds that the tracker will spend tryint to connect to Matomo.setRequestMethodNonBulk()
— Sets the request method to POST, which is recommended when using setTokenAuth() to prevent the token from being recorded in server logs.setProxy()
— If a proxy is needed to look up the address of the Matomo site, set it with thissetOutgoingTrackerCookie()
— Sets a cookie to be sent to the tracking server.getIncomingTrackerCookie()
— Gets a cookie which was set by the tracking server.__construct()
Builds a MatomoTracker object, used to track visits, pages and Goal conversions for a specific website, by using the Matomo Tracking API.
$idSite
(int
) —
Id site to be tracked$apiUrl
(string
) —
"http://example.org/matomo/" or "http://matomo.example.org/" If set, will overwrite MatomoTracker::$URLsetApiUrl()
It accepts the following parameter(s):
$url
(string
) —It does not return anything or a mixed result.
setPageCharset()
By default, Matomo expects utf-8 encoded values, for example for the page URL parameter values, Page Title, etc.
It is recommended to only send UTF-8 data to Matomo. If required though, you can also specify another charset using this function.
It accepts the following parameter(s):
$charset
(string
) —It returns a $this
value.
setUrl()
Sets the current URL being tracked
$url
(string
) —
Raw URL (not URL encoded)$this
value.setUrlReferrer()
Sets the URL referrer used to track Referrers details for new visits.
$url
(string
) —
Raw URL (not URL encoded)$this
value.setGenerationTime()
This method is deprecated and does nothing. It used to set the time that it took to generate the document on the server side.
setPerformanceTimings
$timeMs
(int
) —
Generation time in ms$this
value.setPerformanceTimings()
Sets timings for various browser performance metrics.
https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming
$network
(null
|int
) —
Network time in ms (connectEnd – fetchStart)$server
(null
|int
) —
Server time in ms (responseStart – requestStart)$transfer
(null
|int
) —
Transfer time in ms (responseEnd – responseStart)$domProcessing
(null
|int
) —
DOM Processing to Interactive time in ms (domInteractive – domLoading)$domCompletion
(null
|int
) —
DOM Interactive to Complete time in ms (domComplete – domInteractive)$onload
(null
|int
) —
Onload time in ms (loadEventEnd – loadEventStart)$this
value.clearPerformanceTimings()
Clear / reset all previously set performance metrics.
setAttributionInfo()
Sets the attribution information to the visit, so that subsequent Goal conversions are properly attributed to the right Referrer URL, timestamp, Campaign Name & Keyword.
This must be a JSON encoded string that would typically be fetched from the JS API: matomoTracker.getAttributionInfo() and that you have JSON encoded via JSON2.stringify()
If you call enableCookies() then these referral attribution values will be set to the 'ref' first party cookie storing referral information.
function
— getAttributionInfo() in https://github.com/matomo-org/matomo/blob/master/js/matomo.js$jsonEncoded
(string
) —
JSON encoded array containing Attribution info$this
value.setCustomVariable()
Sets Visit Custom Variable.
See https://matomo.org/docs/custom-variables/
$id
(int
) —
Custom variable slot ID from 1-5$name
(string
) —
Custom variable name$value
(string
) —
Custom variable value$scope
(string
) —
Custom variable scope. Possible values: visit, page, event$this
value.getCustomVariable()
Returns the currently assigned Custom Variable.
If scope is 'visit', it will attempt to read the value set in the first party cookie created by Matomo Tracker ($_COOKIE array).
matomo.js
— getCustomVariable()It accepts the following parameter(s):
$id
(int
) —
Custom Variable integer index to fetch from cookie. Should be a value from 1 to 5$scope
(string
) —
Custom variable scope. Possible values: visit, page, eventReturns: mixed
—
An array with this format: array( 0 => CustomVariableName, 1 => CustomVariableValue ) or false
clearCustomVariables()
Clears any Custom Variable that may be have been set.
This can be useful when you have enabled bulk requests, and you wish to clear Custom Variables of 'visit' scope.
setCustomDimension()
Sets a specific custom dimension
$id
(int
) —
id of custom dimension$value
(string
) —
value for custom dimension$this
value.clearCustomDimensions()
Clears all previously set custom dimensions
getCustomDimension()
Returns the value of the custom dimension with the given id
It accepts the following parameter(s):
$id
(int
) —
id of custom dimensionReturns: string
|null
—
setCustomTrackingParameter()
Sets a custom tracking parameter. This is useful if you need to send any tracking parameters for a 3rd party plugin that is not shipped with Matomo itself. Please note that custom parameters are cleared after each tracking request.
$trackingApiParameter
(string
) —
The name of the tracking API parameter, eg 'bw_bytes'$value
(string
) —
Tracking parameter value that shall be sent for this tracking parameter.$this
value.clearCustomTrackingParameters()
Clear / reset all previously set custom tracking parameters.
setNewVisitorId()
Sets the current visitor ID to a random new one.
$this
value.setIdSite()
Sets the current site ID.
It accepts the following parameter(s):
$idSite
(int
) —It returns a $this
value.
setBrowserLanguage()
Sets the Browser language. Used to guess visitor countries when GeoIP is not enabled
$acceptLanguage
(string
) —
For example "fr-fr"$this
value.setUserAgent()
Sets the user agent, used to detect OS and browser.
If this function is not called, the User Agent will default to the current user agent.
It accepts the following parameter(s):
$userAgent
(string
) —It returns a $this
value.
setClientHints()
Sets the client hints, used to detect OS and browser.
If this function is not called, the client hints sent with the current request will be used.
Supported as of Matomo 4.12.0
$model
(string
) —
Value of the header 'HTTP_SEC_CH_UA_MODEL'$platform
(string
) —
Value of the header 'HTTP_SEC_CH_UA_PLATFORM'$platformVersion
(string
) —
Value of the header 'HTTP_SEC_CH_UA_PLATFORM_VERSION'$fullVersionList
(string
|array
) —
Value of header 'HTTP_SEC_CH_UA_FULL_VERSION_LIST' or an array containing all brands with the structure [['brand' => 'Chrome', 'version' => '10.0.2'], ['brand' => '...]$uaFullVersion
(string
) —
Value of the header 'HTTP_SEC_CH_UA_FULL_VERSION'$this
value.setCountry()
Sets the country of the visitor. If not used, Matomo will try to find the country using either the visitor's IP address or language.
Allowed only for Admin/Super User, must be used along with setTokenAuth().
It accepts the following parameter(s):
$country
(string
) —It returns a $this
value.
setRegion()
Sets the region of the visitor. If not used, Matomo may try to find the region using the visitor's IP address (if configured to do so).
Allowed only for Admin/Super User, must be used along with setTokenAuth().
It accepts the following parameter(s):
$region
(string
) —It returns a $this
value.
setCity()
Sets the city of the visitor. If not used, Matomo may try to find the city using the visitor's IP address (if configured to do so).
Allowed only for Admin/Super User, must be used along with setTokenAuth().
It accepts the following parameter(s):
$city
(string
) —It returns a $this
value.
setLatitude()
Sets the latitude of the visitor. If not used, Matomo may try to find the visitor's latitude using the visitor's IP address (if configured to do so).
Allowed only for Admin/Super User, must be used along with setTokenAuth().
It accepts the following parameter(s):
$lat
(float
) —It returns a $this
value.
setLongitude()
Sets the longitude of the visitor. If not used, Matomo may try to find the visitor's longitude using the visitor's IP address (if configured to do so).
Allowed only for Admin/Super User, must be used along with setTokenAuth().
It accepts the following parameter(s):
$long
(float
) —It returns a $this
value.
enableBulkTracking()
Enables the bulk request feature. When used, each tracking action is stored until the doBulkTrack method is called. This method will send all tracking data at once.
disableBulkTracking()
Disables the bulk request feature. Make sure to call doBulkTrack()
before disabling it if you have stored
tracking actions previously as this method won't be sending any previously stored actions before disabling it.
enableCookies()
Enable Cookie Creation - this will cause a first party VisitorId cookie to be set when the VisitorId is set or reset
$domain
(string
) —
(optional) Set first-party cookie domain. Accepted values: example.com, *.example.com (same as .example.com) or subdomain.example.com$path
(string
) —
(optional) Set first-party cookie path$secure
(bool
) —
(optional) Set secure flag for cookies$httpOnly
(bool
) —
(optional) Set HTTPOnly flag for cookies$sameSite
(string
) —
(optional) Set SameSite flag for cookiesdisableSendImageResponse()
If image response is disabled Matomo will respond with a HTTP 204 header instead of responding with a gif.
doTrackPageView()
Tracks a page view
It accepts the following parameter(s):
$documentTitle
(string
) —
Page title as it will appear in the Actions > Page titles reportReturns: mixed
—
Response string or true if using bulk requests.
setPageviewId()
Override PageView id for every use of doTrackPageView()
. Do not use this if you call doTrackPageView()
multiple times during tracking (if, for example, you are tracking a single page application).
It accepts the following parameter(s):
$idPageview
(string
) —It does not return anything or a mixed result.
getPageviewId()
Returns the PageView id. If the id was manually set using setPageViewId()
, that id will be returned.
If the id was not set manually, the id that was automatically generated in last doTrackPageView()
will
be returned. If there was no last page view, this will be false.
mixed
—
The PageView id as string or false if there is none yet.doTrackEvent()
Tracks an event
It accepts the following parameter(s):
$category
(string
) —
The Event Category (Videos, Music, Games...)$action
(string
) —
The Event's Action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...)$name
(string
|bool
) —
(optional) The Event's object Name (a particular Movie name, or Song name, or File name...)$value
(float
|bool
) —
(optional) The Event's valueReturns: mixed
—
Response string or true if using bulk requests.
doTrackContentImpression()
Tracks a content impression
It accepts the following parameter(s):
$contentName
(string
) —
The name of the content. For instance 'Ad Foo Bar'$contentPiece
(string
) —
The actual content. For instance the path to an image, video, audio, any text$contentTarget
(string
|bool
) —
(optional) The target of the content. For instance the URL of a landing page.Returns: mixed
—
Response string or true if using bulk requests.
doTrackContentInteraction()
Tracks a content interaction. Make sure you have tracked a content impression using the same content name and content piece, otherwise it will not count. To do so you should call the method doTrackContentImpression();
It accepts the following parameter(s):
$interaction
(string
) —
The name of the interaction with the content. For instance a 'click'$contentName
(string
) —
The name of the content. For instance 'Ad Foo Bar'$contentPiece
(string
) —
The actual content. For instance the path to an image, video, audio, any text$contentTarget
(string
|bool
) —
(optional) The target the content leading to when an interaction occurs. For instance the URL of a landing page.Returns: mixed
—
Response string or true if using bulk requests.
doTrackSiteSearch()
Tracks an internal Site Search query, and optionally tracks the Search Category, and Search results Count.
These are used to populate reports in Actions > Site Search.
It accepts the following parameter(s):
$keyword
(string
) —
Searched query on the site$category
(string
) —
(optional) Search engine category if applicable$countResults
(bool
|int
) —
(optional) results displayed on the search result page. Used to track "zero result" keywords.Returns: mixed
—
Response or true if using bulk requests.
doTrackGoal()
Records a Goal conversion
It accepts the following parameter(s):
$idGoal
(int
) —
Id Goal to record a conversion$revenue
(float
) —
Revenue for this conversionReturns: mixed
—
Response or true if using bulk request
doTrackAction()
Tracks a download or outlink
It accepts the following parameter(s):
$actionUrl
(string
) —
URL of the download or outlink$actionType
(string
) —
Type of the action: 'download' or 'link'Returns: mixed
—
Response or true if using bulk request
addEcommerceItem()
Adds an item in the Ecommerce order.
This should be called before doTrackEcommerceOrder(), or before doTrackEcommerceCartUpdate(). This function can be called for all individual products in the cart (or order). SKU parameter is mandatory. Other parameters are optional (set to false if value not known). Ecommerce items added via this function are automatically cleared when doTrackEcommerceOrder() or getUrlTrackEcommerceOrder() is called.
$sku
(string
) —
(required) SKU, Product identifier$name
(string
) —
(optional) Product name$category
(string
|array
) —
(optional) Product category, or array of product categories (up to 5 categories can be specified for a given product)$price
(float
|int
) —
(optional) Individual product price (supports integer and decimal prices)$quantity
(int
) —
(optional) Product quantity. If not specified, will default to 1 in the Reports$this
value.doTrackEcommerceCartUpdate()
Tracks a Cart Update (add item, remove item, update item).
On every Cart update, you must call addEcommerceItem() for each item (product) in the cart, including the items that haven't been updated since the last cart update. Items which were in the previous cart and are not sent in later Cart updates will be deleted from the cart (in the database).
It accepts the following parameter(s):
$grandTotal
(float
) —
Cart grandTotal (typically the sum of all items' prices)Returns: mixed
—
Response or true if using bulk request
doBulkTrack()
Sends all stored tracking actions at once. Only has an effect if bulk tracking is enabled.
To enable bulk tracking, call enableBulkTracking().
string
—
ResponsedoTrackEcommerceOrder()
Tracks an Ecommerce order.
If the Ecommerce order contains items (products), you must call first the addEcommerceItem() for each item in the order. All revenues (grandTotal, subTotal, tax, shipping, discount) will be individually summed and reported in Matomo reports. Only the parameters $orderId and $grandTotal are required.
It accepts the following parameter(s):
$orderId
(string
|int
) —
(required) Unique Order ID. This will be used to count this order only once in the event the order page is reloaded several times. orderId must be unique for each transaction, even on different days, or the transaction will not be recorded by Matomo.$grandTotal
(float
) —
(required) Grand Total revenue of the transaction (including tax, shipping, etc.)$subTotal
(float
) —
(optional) Sub total amount, typically the sum of items prices for all items in this order (before Tax and Shipping costs are applied)$tax
(float
) —
(optional) Tax amount for this order$shipping
(float
) —
(optional) Shipping amount for this order$discount
(float
) —
(optional) Discounted amount in this orderReturns: mixed
—
Response or true if using bulk request
doTrackPhpThrowable()
Tracks a PHP Throwable a crash (requires CrashAnalytics to be enabled in the target Matomo)
It accepts the following parameter(s):
$ex
(Throwable
) —
(required) the throwable to track. The message, stack trace, file location and line number of the crash are deduced from this parameter. The crash type is set to the class name of the Throwable.$category
(string
|null
) —
(optional) a category value for this crash. This can be any information you want to attach to the crash.Returns: mixed
—
Response or true if using bulk request
doTrackCrash()
Track a crash (requires CrashAnalytics to be enabled in the target Matomo)
It accepts the following parameter(s):
$message
(string
) —
(required) the error message.$type
(string
|null
) —
(optional) the error type, such as the class name of an Exception.$category
(string
|null
) —
(optional) a category value for this crash. This can be any information you want to attach to the crash.$stack
(string
|null
) —
(optional) the stack trace of the crash.$location
(string
|null
) —
(optional) the source file URI where the crash originated.$line
(int
|null
) —
(optional) the source file line where the crash originated.$column
(int
|null
) —
(optional) the source file column where the crash originated.Returns: mixed
—
Response or true if using bulk request
doPing()
Sends a ping request.
Ping requests do not track new actions. If they are sent within the standard visit length (see global.ini.php), they will extend the existing visit and the current last action for the visit. If after the standard visit length, ping requests will create a new visit using the last action in the last known visit.
mixed
—
Response or true if using bulk requestsetEcommerceView()
Sets the current page view as an item (product) page view, or an Ecommerce Category page view.
This must be called before doTrackPageView() on this product/category page.
On a category page, you may set the parameter $category only and set the other parameters to false.
Tracking Product/Category page views will allow Matomo to report on Product & Categories conversion rates (Conversion rate = Ecommerce orders containing this product or category / Visits to the product or category)
$sku
(string
) —
Product SKU being viewed$name
(string
) —
Product Name being viewed$category
(string
|array
) —
Category being viewed. On a Product page, this is the product's category. You can also specify an array of up to 5 categories for a given page view.$price
(float
) —
Specify the price at which the item was displayed$this
value.getUrlTrackPageView()
Builds URL to track a page view.
doTrackPageView()
It accepts the following parameter(s):
$documentTitle
(string
) —
Page view name as it will appear in Matomo reportsReturns: string
—
URL to matomo.php with all parameters set to track the pageview
getUrlTrackEvent()
Builds URL to track a custom event.
doTrackEvent()
It accepts the following parameter(s):
$category
(string
) —
The Event Category (Videos, Music, Games...)$action
(string
) —
The Event's Action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...)$name
(string
|bool
) —
(optional) The Event's object Name (a particular Movie name, or Song name, or File name...)$value
(float
|bool
) —
(optional) The Event's valueReturns: string
—
URL to matomo.php with all parameters set to track the pageview
getUrlTrackContentImpression()
Builds URL to track a content impression.
doTrackContentImpression()
It accepts the following parameter(s):
$contentName
(string
) —
The name of the content. For instance 'Ad Foo Bar'$contentPiece
(string
) —
The actual content. For instance the path to an image, video, audio, any text$contentTarget
(string
|false
) —
(optional) The target of the content. For instance the URL of a landing page.Returns: string
—
URL to matomo.php with all parameters set to track the pageview
Exception
— In case $contentName is emptygetUrlTrackContentInteraction()
Builds URL to track a content interaction.
doTrackContentInteraction()
It accepts the following parameter(s):
$interaction
(string
) —
The name of the interaction with the content. For instance a 'click'$contentName
(string
) —
The name of the content. For instance 'Ad Foo Bar'$contentPiece
(string
) —
The actual content. For instance the path to an image, video, audio, any text$contentTarget
(string
|false
) —
(optional) The target the content leading to when an interaction occurs. For instance the URL of a landing page.Returns: string
—
URL to matomo.php with all parameters set to track the pageview
Exception
— In case $interaction or $contentName is emptygetUrlTrackSiteSearch()
Builds URL to track a site search.
doTrackSiteSearch()
It accepts the following parameter(s):
$keyword
(string
) —
$category
(string
) —
$countResults
(int
) —
It returns a string
value.
getUrlTrackGoal()
Builds URL to track a goal with idGoal and revenue.
doTrackGoal()
It accepts the following parameter(s):
$idGoal
(int
) —
Id Goal to record a conversion$revenue
(float
) —
Revenue for this conversionReturns: string
—
URL to matomo.php with all parameters set to track the goal conversion
getUrlTrackAction()
Builds URL to track a new action.
doTrackAction()
It accepts the following parameter(s):
$actionUrl
(string
) —
URL of the download or outlink$actionType
(string
) —
Type of the action: 'download' or 'link'Returns: string
—
URL to matomo.php with all parameters set to track an action
getUrlTrackCrash()
Builds URL to track a crash.
doTrackCrash()
It accepts the following parameter(s):
$message
(string
) —
(required) the error message.$type
(string
|null
) —
(optional) the error type, such as the class name of an Exception.$category
(string
|null
) —
(optional) a category value for this crash. This can be any information you want to attach to the crash.$stack
(string
|null
) —
(optional) the stack trace of the crash.$location
(string
|null
) —
(optional) the source file URI where the crash originated.$line
(int
|null
) —
(optional) the source file line where the crash originated.$column
(int
|null
) —
(optional) the source file column where the crash originated.Returns: string
—
URL to matomo.php with all parameters set to track an action
setForceVisitDateTime()
Overrides server date and time for the tracking requests.
By default Matomo will track requests for the "current datetime" but this function allows you to track visits in the past. All times are in UTC.
Allowed only for Admin/Super User, must be used along with setTokenAuth()
setTokenAuth()
$dateTime
(string
) —
Date with the format 'Y-m-d H:i:s', or a UNIX timestamp. If the datetime is older than one day (default value for tracking_requests_require_authentication_when_custom_timestamp_newer_than), then you must call setTokenAuth() with a valid Admin/Super user token.$this
value.setForceNewVisit()
Forces Matomo to create a new visit for the tracking request.
By default, Matomo will create a new visit if the last request by this user was more than 30 minutes ago. If you call setForceNewVisit() before calling doTrack*, then a new visit will be created for this request.
$this
value.setIp()
Overrides IP address
Allowed only for Admin/Super User, must be used along with setTokenAuth()
setTokenAuth()
$ip
(string
) —
IP string, eg. 130.54.2.1$this
value.setUserId()
Force the action to be recorded for a specific User. The User ID is a string representing a given user in your system.
A User ID can be a username, UUID or an email address, or any number or string that uniquely identifies a user or client.
$userId
(string
) —
Any user ID string (eg. email address, ID, username). Must be non empty. Set to false to de-assign a user id previously set.$this
value.getUserIdHashed()
Hash function used internally by Matomo to hash a User ID into the Visitor ID.
Note: matches implementation of Tracker\Request->getUserIdHashed()
It accepts the following parameter(s):
$id
It returns a string
value.
setVisitorId()
Forces the requests to be recorded for the specified Visitor ID.
Rather than letting Matomo attribute the user with a heuristic based on IP and other user fingeprinting attributes, force the action to be recorded for a particular visitor.
If not set, the visitor ID will be fetched from the 1st party cookie, or will be set to a random UUID.
$visitorId
(string
) —
16 hexadecimal characters visitor ID, eg. "33c31e01394bdc63"$this
value.getVisitorId()
If the user initiating the request has the Matomo first party cookie, this function will try and return the ID parsed from this first party cookie (found in $_COOKIE).
If you call this function from a server, where the call is triggered by a cron or script not initiated by the actual visitor being tracked, then it will return the random Visitor ID that was assigned to this visit object.
This can be used if you wish to record more visits, actions or goals for this visitor ID later on.
string
—
16 hex chars visitor ID stringgetUserAgent()
Returns the currently set user agent.
string
value.getIp()
Returns the currently set IP address.
string
value.getUserId()
Returns the User ID string, which may have been set via: $v->setUserId('username@example.org');
bool
value.deleteCookies()
Deletes all first party cookies from the client
getAttributionInfo()
Returns the currently assigned Attribution Information stored in a first party cookie.
This function will only work if the user is initiating the current request, and his cookies can be read by PHP from the $_COOKIE array.
matomo.js
— getAttributionInfo()string
—
JSON Encoded string containing the Referrer information for Goal conversion attribution.
Will return false if the cookie could not be foundsetTokenAuth()
Some Tracking API functionality requires express authentication, using either the Super User token_auth, or a user with 'admin' access to the website.
The following features require access: - force the visitor IP - force the date & time of the tracking requests rather than track for the current datetime
$token_auth
(string
) —
token_auth 32 chars token_auth string$this
value.setLocalTime()
Sets local visitor time
$time
(string
) —
HH:MM:SS format$this
value.setResolution()
Sets user resolution width and height.
It accepts the following parameter(s):
$width
(int
) —
$height
(int
) —
It returns a $this
value.
setBrowserHasCookies()
Sets if the browser supports cookies This is reported in "List of plugins" report in Matomo.
It accepts the following parameter(s):
$bool
(bool
) —It returns a $this
value.
setDebugStringAppend()
Will append a custom string at the end of the Tracking request.
It accepts the following parameter(s):
$string
(string
) —It returns a $this
value.
setPlugins()
Sets visitor browser supported plugins
It accepts the following parameter(s):
$flash
(bool
) —
$java
(bool
) —
$quickTime
(bool
) —
$realPlayer
(bool
) —
$pdf
(bool
) —
$windowsMedia
(bool
) —
$silverlight
(bool
) —
It returns a $this
value.
disableCookieSupport()
By default, MatomoTracker will read first party cookies from the request and write updated cookies in the response (using setrawcookie).
This can be disabled by calling this function.
getRequestTimeout()
Returns the maximum number of seconds the tracker will spend waiting for a response from Matomo. Defaults to 600 seconds.
setRequestTimeout()
Sets the maximum number of seconds that the tracker will spend waiting for a response from Matomo.
It accepts the following parameter(s):
$timeout
(int
) —It returns a $this
value.
getRequestConnectTimeout()
Returns the maximum number of seconds the tracker will spend trying to connect to Matomo.
Defaults to 300 seconds.
setRequestConnectTimeout()
Sets the maximum number of seconds that the tracker will spend tryint to connect to Matomo.
It accepts the following parameter(s):
$timeout
(int
) —It returns a $this
value.
setRequestMethodNonBulk()
Sets the request method to POST, which is recommended when using setTokenAuth() to prevent the token from being recorded in server logs. Avoid using redirects when using POST to prevent the loss of POST values. When using Log Analytics, be aware that POST requests are not parseable/replayable.
$method
(string
) —
Either 'POST' or 'GET'$this
value.setProxy()
If a proxy is needed to look up the address of the Matomo site, set it with this
It accepts the following parameter(s):
$proxy
(string
) —
IP as string, for example "173.234.92.107"$proxyPort
(int
) —It does not return anything or a mixed result.
setOutgoingTrackerCookie()
Sets a cookie to be sent to the tracking server.
It accepts the following parameter(s):
$name
$value
It does not return anything or a mixed result.
getIncomingTrackerCookie()
Gets a cookie which was set by the tracking server.
It accepts the following parameter(s):
$name
Returns: bool
|string
—