Skip to main content

PHP SDK for Statsig

The Basics

Get started in a few quick steps.

  1. Create a free account on statsig.com
  2. Install the SDK
  3. Initialize the SDK
  4. Check Feature Gates, Dynamic Configs, or Experiments
  5. Send logs to Statsig
  6. Log a custom event

Step 1 - Create a free account on www.statsig.com

You could skip this for now, but you will need an SDK Key and some Feature Gates or Dynamic Configs to use with the SDK in just a minute.

Step 2 - Install the SDK

You can install the SDK using composer

composer require statsig/statsigsdk

The SDK is also open source and hosted on github. The package is published to packagist.

Step 3 - Initialize the SDK

After installation, you will need to initialize the SDK using a Server Secret Key from the statsig console.

There is also a parameter options that requires you to pass in a storage adapter for storing configurations and event logs. In this below example, we use a local file storage adapter, but you can write your own to plug in Redis or another storage solution. Create an adapter that implements Statsig\Adapters\IConfigAdapter if you do not want to use the local file storage adapter.

use Statsig\StatsigServer;
use Statsig\StatsigOptions;
use Statsig\Adapters\LocalFileConfigAdapter;
use Statsig\Adapters\LocalFileLoggingAdapter;

$config_adapter = new LocalFileConfigAdapter();
$logging_adapter = new LocalFileLoggingAdapter();
$options = new StatsigOptions($config_adapter, $logging_adapter);
$this->statsig = new StatsigServer("server-sdk-key", $options);

Step 4 - Fetch Feature Gates, Dynamic Configs, or Experiments

NOTE: The php SDK currently does not support Segments that are using ID lists. Please file an issue on github if you need this feature, or reach out to us on our slack channel

Now that your SDK is initialized, let's fetch a Feature Gate. Feature Gates can be used to create logic branches in code that can be rolled out to different users from the Statsig Console. Gates are always CLOSED or OFF (think return false;) by default.

From this point on, all APIs will require you to specify the user (see Statsig user) associated with the request. For example, check a gate for a certain user like this:

use Statsig\StatsigUser;

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

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

Feature Gates can be very useful for simple on/off switches, with optional but advanced user targeting. However, if you want to be able send a different set of values (strings, numbers, and etc.) to your clients based on specific user attributes, e.g. country, Dynamic Configs can help you with that. The API is very similar to Feature Gates, but you get an entire json object you can configure on the server and you can fetch typed parameters from it. For example:

$this->statsig->getConfig($user, "<config_name>");

Then we have Experiments, which you can use to run A/B/n experiments and use advanced features like layers (coming soon) to avoid collision and enable quicker iterations with parameter reuse.

$this->statsig->getExperiment($user, "test_config");

Step 5 - Log a custom event

Now that you have a Feature Gate or an Experiment set up, you may want to track some custom events and see how your new features or different experiment groups affect these events. This is super easy with Statsig - simply call the Log Event API and specify the user and event name to log; you additionally provide some value and/or an object of metadata to be logged together with the event:

use Statsig\StatsigEvent;

$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:

$this->statsig->flush();

Step 6 (Optional) - Sync Gate/Experiment/Config Defintions and Send Logs

To keep your configurations up to date, and send event data to Statsig, you can create two cron jobs.

Sync

The first runs sync.php to download the latest definition of gates/configs/experiments from Statsig, and save it to a config file locally. If you do not update this file, your gate/config/experiment values may be stale and will be refetched during a request, which may lead to slower response times.

# Run once
php sync.php --secret <STATSIG_SECRET_KEY>
# 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

Alternatively, you may provide your own custom adapter that implements Statsig\Adapters\IConfigAdapter if you do not want to use the local file storage adapter.

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, send.php will use the Statsig LocalFileLoggingAdapter which writes to /tmp/statsig.logs

Send

The second runs send.php to send the exposure data and log events to statsig. Without this data, your events will need to be logged during the lifetime of the request, which may lead to slower resposne times.

# Run once
php send.php --secret <STATSIG_SECRET_KEY>
# Create a cron job that runs as statsigsync 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

Alternatively, you may provide your own custom adapter that implements Statsig\Adapters\ILoggingConfig if you do not want to use the local file storage adapter.

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, send.php will use the Statsig LocalFileConfigAdapter which writes to /tmp/statsig.configs

Statsig User

When calling APIs that require a user, you should pass as much information as possible in order to take advantage of advanced gate and config conditions (like country or OS/browser level checks), and correctly measure impact of your experiments on your metrics/events. The userID field is required because it's needed to provide a consistent experience for a given user (click here to understand further why it's important to always provide a userID).

Besides userID, we also have customIDs, email, ip, userAgent, country, locale and appVersion as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the custom field and be able to create targeting based on them.

Note: You must provide userID or at least 1 customID or an exception will be thrown.

Have sensitive user PII data that should not be logged?

No problem, we have a solution for it! On the StatsigUser object we also have a field called privateAttributes, which is a simple object/dictionary that you can use to set private user attributes. Any attribute set in privateAttributes will only be used for evaluation/targeting, and removed from any logs before they are sent to Statsig server.

For example, if you have feature gates that should only pass for users with emails ending in "@statsig.com", but do not want to log your users' email addresses to Statsig, you can simply add the key-value pair { email: "my_user@statsig.com" } to privateAttributes on the user and that's it!

Statsig Options

StatsigOptions is a common configuration parameter across Statsig SDKs. For the PHP sdk, the following are configurable:

  • IConfigAdapter (required) - A class that implements IConfigAdapter. Statsig provides the LocalFileConfigAdapter, but you can write your own.
  • ILoggingAdapter - A class that implements ILoggingAdapter. Statsig provides the LocalFileLoggingAdapter, but you can write your own. If no adapter is provided, logs must be sent during the request.

You can also configure:

  • The environment (see using environments) via setEnvironmentTier("production" | "staging" | "development")
  • The event queue size (How many events to track before they are sent to Statsig) via setEventQueueSize(int $size).

FAQ

How do I run experiments for logged out users?

You can run experiments for arbitrary unit IDs (sessionID, groupID, etc), rather than at the userID level, if you choose. These custom unit IDs must be predefined in your Statsig project, and then selected in the Experiment creation flow. For more information, see our guide on experimenting on custom ID types

Using the httpAPI instead

If you want a simple snippet for using the http api in php, you may find the following gist useful. It exposes functions to checkGate, getConfig, getExperiment, and logEvent.

Note that the user parameter to each of these functions follows the Statsig User definition for Server SDKs.