On this page

Legacy PHP Server SDK

Statsig's Legacy Server SDK for PHP applications

Github Repository

Setup the SDK

  1. Install the SDK

    You can install the PHP SDK using composer.

    bash
    composer require statsig/statsigsdk
    
    The SDK is also open source and hosted on github. The package is published to packagist.

    To successfully use the PHP SDK, you need to:

    1. Install it
    2. Provide a storage adapter to cache config and event logs (easy default exists)
    3. Schedule a Cron job to poll for config changes and flush event logs to Statsig
    4. Initialize and use the SDK
  2. Initialize the SDK

    After installation, initialize the SDK using a Server Secret Key from the Statsig console.

    Do NOT embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console.

    The options parameter requires a storage adapter for storing configurations and event logs. The example below uses a local file storage adapter, but you can write your own to connect Redis or another storage solution.

    Create an adapter that implements Statsig\Adapters\IConfigAdapter connected to your caching solution. By default, a local file solution is provided, which is useful for initial setup but is not suitable for production settings.

    For help with the interface and implementing an adapter, browse the adapters directory in the open source SDK repository.
    php
    require_once __DIR__ . '/vendor/autoload.php'; // path to installation folder
    
    use Statsig\StatsigServer;
    use Statsig\StatsigOptions;
    use Statsig\Adapters\LocalFileDataAdapter;
    use Statsig\Adapters\LocalFileLoggingAdapter;
    
    $config_adapter = new LocalFileDataAdapter();
    $logging_adapter = new LocalFileLoggingAdapter();
    $options = new StatsigOptions($config_adapter, $logging_adapter);
    $this->statsig = new StatsigServer("server-sdk-key", $options);
    

    🔥 Warning - You need to schedule a job 🔥

    V3.0+

    If you don't configure a job to update the config values, the SDK doesn't fire a network request to fetch the latest config value anymore, and config values fetched earlier are used instead.

    Refer to Cron Jobs.

Working with the SDK

Checking a Feature Flag/Gate

After the SDK is initialized, you can check a Feature Gate. Feature Gates create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (return false;) by default.All APIs require you to specify the user (refer to Statsig user) associated with the request. For example, to check a gate for a user:
php
use Statsig\StatsigUser;

$user = StatsigUser::withUserID("123");
$user->setEmail("testuser@statsig.com");

$this->statsig->checkGate($user, "<gate_name>");

Reading a Dynamic Config

Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use Dynamic Configs. The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters.
php
$this->statsig->getConfig($user, "<config_name>");

Getting a Layer/Experiment

Use Layers/Experiments to run A/B/n experiments. Two APIs are available, but Statsig recommends layers for faster iterations with parameter reuse.
php
// Values via getLayer

$layer = $this->statsig->getLayer($user, "user_promo_experiments");
$title = $layer->get("title", "Welcome to Statsig!");
$discount = $layer->get("discount", 0.1);

// or, via getExperiment

$title_experiment = $this->statsig->getExperiment($user, "new_user_promo_title");
$price_experiment = $this->statsig->getExperiment($user, "new_user_promo_price");
$title = $title_experiment->get("title", "Welcome to Statsig!")
$discount = $price_experiment->get("discount", 0.1)

...

$price = $msrp * (1 - $discount)

Logging an Event

To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object:

php
$event = new StatsigEvent("purchase");
$event->setUser($user);
$event->setValue("subscription");
$event->setMetadata(array("promotion" => "2022 deals"));
$this->statsig->logEvent($event);

At the end of the request, you can flush events to the log file using:

php
$this->statsig->flush();
For more about identifying users, group analytics, and best practices, go to the logging events guide.

Cron jobs

To keep your configurations up to date and send event data to Statsig, create two jobs. These are documented as cron jobs, but you can use any out-of-band process. If you are using Laravel, you can use Commands to run them locally and on a schedule.

Sync

The first job runs sync.php to download the latest definition of gates/configs/experiments from Statsig and save it to a local config file. If this file is not updated, gate/config/experiment values may be stale. The SDK refetches stale values during a request, which can cause slower response times.

bash
# Run once
php sync.php --secret <STATSIG_SECRET_KEY>
bash
# Create a cron job that runs as statsigsync every minute
echo '*/1 * * * * statsigsync php /my/path/to/statsig/sync.php --secret <STATSIG_SECRET_KEY> > /dev/null' | sudo tee /etc/cron.d/statsigsync
sudo service cron reload    # reload the cron daemon

You should provide your own custom adapter that implements Statsig\Adapters\IDataAdapter

bash
php send.php --secret <STATSIG_SECRET_KEY> \
    --adapter-class Namespace\For\MyConfigAdapter \
    --adapter-path /path/to/MyConfigAdapter.php \
    --adapter-arg an_argument_for_my_adapter \
    --adapter-arg another_argument

By default, sync.php uses the Statsig LocalFileDataAdapter which writes to /tmp/statsig.configs.

Send

The second job runs send.php to send exposure data and log events to Statsig. Without this, events are logged during the lifetime of the request, which can cause slower response times.

bash
# Run once
php send.php --secret <STATSIG_SECRET_KEY>
bash
# Create a cron job that runs as statsigdata every minute
echo '*/1 * * * * statsigdata php /my/path/to/statsig/send.php --secret <STATSIG_SECRET_KEY> > /dev/null' | sudo tee /etc/cron.d/statsigdata
sudo service cron reload    # reload the cron daemon

You should provide your own custom adapter that implements Statsig\Adapters\ILoggingAdapter

bash
php send.php --secret <STATSIG_SECRET_KEY> \
     --adapter-class Namespace\For\MyLoggingAdapter \
     --adapter-path /path/to/MyLoggingAdapter.php \
     --adapter-arg an_argument_for_my_adapter \
     --adapter-arg another_argument

By default, send.php uses the Statsig LocalFileDataAdapter which writes to /tmp/statsig.logs.

Statsig User

When calling APIs that require a user, pass as much information as possible to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and to correctly measure the impact of your experiments on your metrics/events. At least one identifier (userID or customID) is required to provide a consistent experience for a given user. Refer to userID requirements for more detail.

In addition to userID, email, ip, userAgent, country, locale, and appVersion are available as top-level fields on StatsigUser. You can also pass any key-value pairs in an object/dictionary to the custom field to create targeting based on them.

Typing on the StatsigUser object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but evaluation results for other types are not guaranteed. For example, an array set as a custom field is only compared as a string: there is no operator to match a value within that array.

Private Attributes

To keep sensitive user PII data out of logs, use the privateAttributes field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. Any attribute set in privateAttributes is used only for evaluation/targeting and is removed from all logs before Statsig sends them to its servers.

For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair { email: "my_user@statsig.com" } to privateAttributes on the user.

Was this helpful?