Search by

simplestats-io / php-client

Sairahcaz

Plain PHP client for SimpleStats analytics. Track visitors, registrations, and payments. Discover which channels actually drive revenue, not just traffic. Server-side, GDPR compliant.

Package info

github.com/simplestats-io/php-client

pkg:composer/simplestats-io/php-client

Statistics

Installs: 91

Dependents: 1

Suggesters: 0

Stars: 2

Open Issues: 0

v1.1.0 2026-12-01 13:18 UTC

This package is auto-updated.

Last update: 2026-12-01 14:24:19 UTC


README

Latest Version on Packagist Tests Check & fix styling License

This is the official plain PHP client to send tracking data to https://simplestats.io. It works with any PHP 8.2+ application, no framework required.

For Laravel applications, use the dedicated Laravel Client instead, which provides automatic middleware, observers, and queue integration.

Introduction

SimpleStats is analytics that goes beyond simple page views. Track visitors, registrations, and payments. Discover which channels actually drive revenue, not just traffic. With server-side tracking and filtering via UTM codes, you get detailed analysis of marketing efforts and clearly see which channels drive revenue. Effortlessly evaluate ROI, identify cost-effective user acquisition channels, and pinpoint the most effective performance channels. SimpleStats is fully GDPR compliant and unaffected by ad blockers since all tracking occurs server-side.

screenshot

Installation

composer require simplestats-io/php-client

Quick Start

use SimpleStatsIo\PhpClient\SimplestatsClient;
use SimpleStatsIo\PhpClient\TrackingData;
use SimpleStatsIo\PhpClient\VisitorHashGenerator;

$client = new SimplestatsClient([
    'api_token' => 'your-api-token',
]);

// Generate a GDPR-compliant visitor hash
$visitorHash = VisitorHashGenerator::generate(
    ip: $_SERVER['REMOTE_ADDR'],
    userAgent: $_SERVER['HTTP_USER_AGENT'],
    secretKey: 'your-secret-key'
);

// Auto-extract tracking data from the current request
$trackingData = TrackingData::fromGlobals(appUrl: 'https://yourapp.com');

// Track the visitor
$client->trackVisitor($visitorHash, $trackingData);

Configuration

Pass a configuration array when creating the client:

$client = new SimplestatsClient([
    'api_token'           => 'your-api-token',                 // Required
    'api_url'             => 'https://simplestats.io/api/v1/', // Optional
    'timeout'             => 5,                                // Optional
    'max_retries'         => 3,                                // Optional
    'enabled'             => true,                             // Optional
    'bot_detection_cache' => null,                             // Optional
]);
  • api_token (string, required): your project API token from SimpleStats.
  • api_url (string, default https://simplestats.io/api/v1/): API base URL, change it for self-hosted.
  • timeout (int, default 5): HTTP request timeout in seconds.
  • max_retries (int, default 3): number of retries on transient failures.
  • enabled (bool, default true): set to false to disable all tracking.
  • bot_detection_cache (DeviceDetector\Cache\CacheInterface, default: file cache in the temp dir): cache for the bot detection, see Bot Filtering.

When tracking is disabled, all methods return an empty array without making any HTTP requests.

Usage

Tracking Visitors

Track anonymous visitors with optional UTM parameters and metadata:

$client->trackVisitor(
    visitorHash: $visitorHash,
    trackingData: $trackingData,
    time: new DateTimeImmutable() // optional, defaults to now
);

Bot Filtering

trackVisitor() does not send visitors whose user agent belongs to a bot, crawler, headless browser or HTTP library (e.g. curl), and returns an empty array for them, just like when tracking is disabled. The check uses matomo/device-detector and the same rules as the SimpleStats backend. A visitor without a user agent is sent, and if the detection fails for any reason, the visitor is sent as well.

By default the parsed rules are kept as small PHP files in a private directory of the system temp dir (one directory per detector version, readable only by the PHP user), so they are not parsed again in every request, and OPcache keeps them in memory. If that directory cannot be used, the rules are parsed per request and tracking keeps working. To use your own cache instead, e.g. a PSR-16 cache through device-detector's bridge:

use DeviceDetector\Cache\PSR16Bridge;

$client = new SimplestatsClient([
    'api_token' => 'your-api-token',
    'bot_detection_cache' => new PSR16Bridge($yourPsr16Cache),
]);

Tracking User Registrations

$client->trackUser(
    id: $user->id,
    registeredAt: new DateTimeImmutable($user->created_at),
    trackingData: $trackingData, // optional
    addLogin: true               // optional, also track a login event
);

Tracking Logins

$client->trackLogin(
    userId: $user->id,
    userRegisteredAt: new DateTimeImmutable($user->created_at),
    ip: $_SERVER['REMOTE_ADDR'],       // optional
    userAgent: $_SERVER['HTTP_USER_AGENT'], // optional
    time: new DateTimeImmutable()       // optional, defaults to now
);

Tracking Payments

Amounts must be in cents (e.g., 2000 = $20.00). Currency must be ISO 4217 (EUR, USD, GBP, etc.).

Associate a payment with either a user or a visitor:

// Payment linked to a registered user
$client->trackPayment(
    id: $payment->id,
    gross: 2000,
    net: 1680,
    currency: 'EUR',
    time: new DateTimeImmutable($payment->created_at),
    userId: $user->id,
    userRegisteredAt: new DateTimeImmutable($user->created_at)
);

// Payment linked to an anonymous visitor (e.g., guest checkout)
$client->trackPayment(
    id: $payment->id,
    gross: 2000,
    net: 1680,
    currency: 'EUR',
    time: new DateTimeImmutable($payment->created_at),
    visitorHash: $visitorHash
);

Tracking Custom Events

$client->trackCustomEvent(
    id: 'evt_123',
    name: 'subscription_upgraded',
    time: new DateTimeImmutable(),  // optional, defaults to now
    userId: $user->id,              // optional
    userRegisteredAt: new DateTimeImmutable($user->created_at) // optional
);

Tracking Data

The TrackingData class holds visitor metadata (IP, user agent, UTM parameters, referer, page entry).

Auto-extract from the current request

$trackingData = TrackingData::fromGlobals(appUrl: 'https://yourapp.com');

This automatically extracts:

  • IP address from proxy-aware headers (Cloudflare, Akamai, X-Forwarded-For, X-Real-IP, REMOTE_ADDR)
  • User agent from the request
  • UTM parameters from query string (utm_source, utm_medium, utm_campaign, utm_term, utm_content, ref, adGroup, adGroupId)
  • Referer domain from the HTTP referer header
  • Page entry path (URI without query string)

Build manually

$trackingData = new TrackingData(
    ip: '203.0.113.50',
    userAgent: 'Mozilla/5.0 ...',
    referer: 'google.com',
    source: 'google',
    medium: 'cpc',
    campaign: 'spring_sale',
    term: 'analytics tool',
    content: 'banner_ad',
    pageEntry: '/pricing',
);

Visitor Hash Generator

Generate GDPR-compliant anonymized visitor identifiers. The hash rotates daily to prevent long-term tracking.

use SimpleStatsIo\PhpClient\VisitorHashGenerator;

$hash = VisitorHashGenerator::generate(
    ip: $_SERVER['REMOTE_ADDR'],
    userAgent: $_SERVER['HTTP_USER_AGENT'],
    secretKey: 'your-secret-key',
    date: '2024-06-15' // optional, defaults to today
);

The generator creates a SHA-256 hash from IP + User-Agent + date + secret key, truncated to 32 characters. The daily date rotation ensures hashes are not persistent across days, keeping visitor tracking fully anonymous.

Tracking Rules

The SimpleStatsIo\PhpClient\Rules namespace holds the framework-agnostic rules that the SimpleStats backend and the Laravel Client use as well, so all of them track identically. You can use them in your own integration:

Class Purpose
Bot::isBot($userAgent, $cache = null) Whether a user agent is a bot, crawler, headless browser or HTTP library (empty counts as bot)
VisitorHash::make($ip, $userAgent, $day, $salt) The daily rotating visitor hash (used by VisitorHashGenerator)
Host::extract($url) / Host::isOwn($url, $ownDomains) Bare host without www., and whether it is one of your own domains (subdomains are not)
PagePath::normalize($path) Page path as SimpleStats stores it, null for assets and files that are no pages
PageView::qualifies($method, $status, $contentType, $headers) Whether a request is a page view a person saw (no prefetch, no XHR, an HTML response)
TrackingCodes::resolve($query) UTM parameters and their aliases from a query array
SubscriptionInterval::fromBillingCycle($unit, $count) Maps a billing cycle (e.g. month x 3) to the interval of a subscription payment

Headers are passed as an array with lowercase names.

Error Handling

The client throws specific exceptions you can catch:

use SimpleStatsIo\PhpClient\Exceptions\ConfigurationException;
use SimpleStatsIo\PhpClient\Exceptions\ApiRequestFailed;

try {
    $client->trackVisitor($visitorHash, $trackingData);
} catch (ConfigurationException $e) {
    // Invalid configuration (e.g., missing api_token)
} catch (ApiRequestFailed $e) {
    // API request failed after retries
    $e->getMessage();    // Error description
    $e->statusCode;      // HTTP status code
    $e->responseBody;    // Raw response body
}

The HTTP client automatically retries on transient failures (connection errors, 429, 5xx) with exponential backoff.

Performance: Non-Blocking Tracking

By default, all tracking calls are synchronous and block the current request. In production, you should avoid adding latency to your user-facing responses. Here are a few strategies:

  • fastcgi_finish_request() (recommended for PHP-FPM): Send the response to the client first, then run tracking calls afterwards. Zero dependencies, works out of the box with PHP-FPM.
  • File/SQLite queue with cron: Write tracking data to a local file or SQLite database, then process it in the background with a cron job. Most reliable approach, but requires a worker setup.
  • Guzzle async requests: Use Guzzle's requestAsync() combined with fastcgi_finish_request() to run multiple tracking calls in parallel after the response is sent.
// Example: fastcgi_finish_request()
echo $responseBody;
fastcgi_finish_request(); // Response is delivered to the client

$client->trackVisitor($visitorHash, $trackingData); // Runs in the background

Testing

composer test

Documentation

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.