PiwikTracker

PiwikTracker implements the Piwik Tracking Web API.

The PHP Tracking Client provides all features of the Javascript Tracker, such as Ecommerce Tracking, Custom Variable, Event tracking and more. Functions are named the same as the Javascript functions.

See introduction docs at: http://piwik.org/docs/tracking-api/

Example: using the PHP PiwikTracker class

The following code snippet is an advanced example of how to track a Page View using the Tracking API PHP client.

 $t = new PiwikTracker( $idSite = 1, 'http://example.org/piwik/');

 // Optional function calls
 $t->setUserAgent( "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB) Firefox/3.6.6");
 $t->setBrowserLanguage('fr');
 $t->setLocalTime( '12:34:06' );
 $t->setResolution( 1024, 768 );
 $t->setBrowserHasCookies(true);
 $t->setPlugins($flash = true, $java = true, $director = false);

 // set a Custom Variable called 'Gender'
 $t->setCustomVariable( 1, 'gender', 'male' );

 // If you want to force the visitor IP, or force the server date time to a date in the past,
 // it is required to authenticate the Tracking request by calling setTokenAuth
 // You can pass the Super User token_auth or any user with 'admin' privilege on the website $idSite
 $t->setTokenAuth( $token_auth );
 $t->setIp( "134.10.22.1" );
 $t->setForceVisitDateTime( '2011-04-05 23:55:02' );

 // if you wanted to force to record the page view or conversion to a specific visitorId
 // $t->setVisitorId( "33c31e01394bdc63" );
 // Mandatory: set the URL being tracked
 $t->setUrl( $url = 'http://example.org/store/list-category-toys/' );

 // Finally, track the page view with a Custom Page Title
 // In the standard JS API, the content of the <title> tag would be set as the page title
 $t->doTrackPageView('This is the page title');

Example: tracking Ecommerce interactions

Here is an example showing how to track Ecommerce interactions on your website, using the PHP Tracking API. Usually, Ecommerce tracking is done using standard Javascript code, but it is very common to record Ecommerce interactions after the fact (for example, when payment is done with Paypal and user doesn't come back on the website after purchase). For more information about Ecommerce tracking in Piwik, check out the documentation: Tracking Ecommerce in Piwik.

 $t = new PiwikTracker( $idSite = 1, 'http://example.org/piwik/');

 // Force IP to the actual visitor IP
 $t->setTokenAuth( $token_auth );
 $t->setIp( "134.10.22.1" );

 // Example 1: on a Product page, track an "Ecommerce Product view"
 $t->setUrl( $url = 'http://www.mystore.com/Endurance-Shackletons-Legendary-Antarctic-Expedition' );
 $t->setEcommerceView($sku = 'SKU0011', $name = 'Endurance - Shackleton', $category = 'Books');
 $t->doTrackPageView( 'Endurance Shackletons Legendary Antarctic Expedition - Mystore.com');

 // Example 2: Tracking Ecommerce Cart containing 2 products
 $t->addEcommerceItem($sku = 'SKU0011', $name = 'Endurance - Shackleton' , $category = 'Books', $price = 17, $quantity = 1);
 // Note that when setting a product category, you can specify an array of up to 5 categories to track for this product
 $t->addEcommerceItem($sku = 'SKU0321', $name = 'Amélie' , $categories = array('DVD Foreign','Best sellers','Our pick'), $price = 25, $quantity = 1);
 $t->doTrackEcommerceCartUpdate($grandTotal = 42);

 // Example 3: Tracking Ecommerce Order
 $t->addEcommerceItem($sku = 'SKU0011', $name = 'Endurance - Shackleton' , $category = 'Books', $price = 17, $quantity = 1);
 $t->addEcommerceItem($sku = 'SKU0321', $name = 'Amélie' , $categories = array('DVD Foreign','Best sellers','Our pick'), $price = 25, $quantity = 1);
 $t->doTrackEcommerceOrder($orderId = 'B000111387', $grandTotal = 55.5, $subTotal = 42, $tax = 8, $shipping = 5.5, $discount = 10);

Note: authenticating with the token_auth

To set the visitor IP, or the date and time of the visit, or to force to record the visit (or page, or goal conversion) to a specific Visitor ID, you must call setTokenAuth( $token_auth ). The token_auth must be either the Super User token_auth, or the token_auth of any user with 'admin' permission for the website you are recording data against.

Properties

This class defines the following properties:

$URL

Piwik base URL, for example http://example.org/piwik/ Must be set before using the class by calling PiwikTracker::$URL = 'http://yourwebsite.org/piwik/';

Signature

$DEBUG_APPEND_URL

Signature

$DEBUG_LAST_REQUESTED_URL

Used in tests to output useful error messages.

Signature

Methods

The class defines the following methods:

__construct()

Builds a PiwikTracker object, used to track visits, pages and Goal conversions for a specific website, by using the Piwik Tracking API.

Signature

setPageCharset()

By default, Piwik 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 Piwik. If required though, you can also specify another charset using this function.

Signature

setUrl()

Sets the current URL being tracked

Signature

setUrlReferrer()

Sets the URL referrer used to track Referrers details for new visits.

Signature

setGenerationTime()

Sets the time that generating the document on the server side took.

Signature

setUrlReferer()

Signature

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: piwikTracker.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.

See Also

Signature

setCustomVariable()

Sets Visit Custom Variable.

See http://piwik.org/docs/custom-variables/

Signature

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 Piwik Tracker ($_COOKIE array).

See Also

Signature

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.

Signature

setNewVisitorId()

Sets the current visitor ID to a random new one.

Signature

setIdSite()

Sets the current site ID.

Signature

setBrowserLanguage()

Sets the Browser language.

Used to guess visitor countries when GeoIP is not enabled

Signature

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.

Signature

setCountry()

Sets the country of the visitor.

If not used, Piwik 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().

Signature

setRegion()

Sets the region of the visitor.

If not used, Piwik 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().

Signature

setCity()

Sets the city of the visitor.

If not used, Piwik 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().

Signature

setLatitude()

Sets the latitude of the visitor.

If not used, Piwik 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().

Signature

setLongitude()

Sets the longitude of the visitor.

If not used, Piwik 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().

Signature

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.

Signature

enableCookies()

Enable Cookie Creation - this will cause a first party VisitorId cookie to be set when the VisitorId is set or reset

Signature

doTrackPageView()

Tracks a page view

Signature

doTrackEvent()

Tracks an event

Signature

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.

Signature

doTrackGoal()

Records a Goal conversion

Signature

doTrackAction()

Tracks a download or outlink

Signature

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.

Signature

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).

Signature

doBulkTrack()

Sends all stored tracking actions at once.

Only has an effect if bulk tracking is enabled.

To enable bulk tracking, call enableBulkTracking().

Signature

doTrackEcommerceOrder()

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 Piwik reports. Only the parameters $orderId and $grandTotal are required.

Signature

setEcommerceView()

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. It will set 3 custom variables of scope "page" with the SKU, Name and Category for this page view. Note: Custom Variables of scope "page" slots 3, 4 and 5 will be used.

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 Piwik to report on Product & Categories conversion rates (Conversion rate = Ecommerce orders containing this product or category / Visits to the product or category)

Signature

getUrlTrackPageView()

Builds URL to track a page view.

See Also

Signature

getUrlTrackEvent()

Builds URL to track a custom event.

See Also

Signature

getUrlTrackSiteSearch()

Builds URL to track a site search.

See Also

Signature

getUrlTrackGoal()

Builds URL to track a goal with idGoal and revenue.

See Also

Signature

getUrlTrackAction()

Builds URL to track a new action.

See Also

Signature

setForceVisitDateTime()

Overrides server date and time for the tracking requests.

By default Piwik 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 Super User, must be used along with setTokenAuth()

See Also

Signature

setForceNewVisit()

Forces Piwik to create a new visit for the tracking request.

By default, Piwik 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.

Allowed only for Super User, must be used along with setTokenAuth()

See Also

Signature

setIp()

Overrides IP address

Allowed only for Super User, must be used along with setTokenAuth()

See Also

Signature

setVisitorId()

Forces the requests to be recorded for the specified Visitor ID rather than using the heuristics based on IP and other attributes.

Allowed only for Admin/Super User, must be used along with setTokenAuth().

You may set the Visitor ID based on a user attribute, for example the user email: $v->setVisitorId( substr(md5( $userEmail ), 0, 16));

If not set, the visitor ID will be fetched from the 1st party cookie, or will be set to a random UUID.

See Also

Signature

getVisitorId()

If the user initiating the request has the Piwik 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.

Signature

deleteCookies()

Deletes all first party cookies from the client

Signature

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.

See Also

Signature

setTokenAuth()

Some Tracking API functionnality 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 - force Piwik to track the requests to a specific VisitorId rather than use the standard visitor matching heuristic

Signature

setLocalTime()

Sets local visitor time

Signature

setResolution()

Sets user resolution width and height.

Signature

setBrowserHasCookies()

Sets if the browser supports cookies This is reported in "List of plugins" report in Piwik.

Signature

setDebugStringAppend()

Will append a custom string at the end of the Tracking request.

Signature

setPlugins()

Sets visitor browser supported plugins

Signature

disableCookieSupport()

By default, PiwikTracker 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.

Signature

getRequestTimeout()

Returns the maximum number of seconds the tracker will spend waiting for a response from Piwik.

Defaults to 600 seconds.

Signature

setRequestTimeout()

Sets the maximum number of seconds that the tracker will spend waiting for a response from Piwik.

Signature