Legacy PHP Server SDK
Statsig's Legacy Server SDK for PHP applications
This is a legacy feature. It is still supported but no longer actively developed; a newer replacement is recommended for new projects.
Setup the SDK
Install the SDK
You can install the PHP SDK using composer.
bashcomposer require statsig/statsigsdkThe SDK is also open source and hosted on github. Statsig publishes the package to packagist.
To successfully use the PHP SDK, you need to:
- Install it
- Provide a storage adapter to cache config and event logs (easy default exists)
- Schedule a Cron job to poll for config changes and flush event logs to Statsig
- Initialize and use the SDK
Initialize the SDK
After installation, initialize the SDK using a Server Secret Key from the Statsig console.
Don't 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
optionsparameter 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\IConfigAdapterconnected to your caching solution. By default, the SDK provides a local file solution, which is useful for initial setup but isn't suitable for production settings.For help with the interface and implementing an adapter, browse the adapters directory in the open source SDK repository.
phprequire_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 instead uses config values fetched earlier.
Refer to Cron Jobs.
Working with the SDK
Checking a Feature Flag/Gate
After you initialize the SDK, you can check a Feature Gate. Feature Gates create logic branches in code that you can roll 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:
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.
$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.
// 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:
$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();
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. This guide documents these as cron jobs, but you can use any out-of-band process. If you're 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 the job doesn't update this file, gate/config/experiment values may be stale. The SDK refetches stale values during a request, which can cause 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
You should provide your own custom adapter that implements Statsig\Adapters\IDataAdapter
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, the SDK logs events during the lifetime of the request, which can cause slower response times.
# Run once
php send.php --secret <STATSIG_SECRET_KEY>
# 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
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. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to userID requirements for more detail.
In addition to userID, the top-level fields on StatsigUser are email, ip, userAgent, country, locale, and appVersion. 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 Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's 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. The SDK uses any attribute set in privateAttributes only for evaluation/targeting and removes it 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?