PHP Server SDK
Installation
You can install the PHP SDK using composer.
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
- 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, you will need to 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.
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.
You should create an adapter that implements Statsig\Adapters\IConfigAdapter
that hooks up to your caching solution. By default, we provide a local file solution that can be useful for first time setup but is challenging to work with in production settings.
For help with the interface and implementing an adapter, browse the adapters directory in the open source SDK repository.
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 do not configure a job to update the config values, SDK does not fire a network request to fetch the latest config value anymore, instead, config values fetched earlier will be used.
See Cron Jobs
Working with the SDK
Checking a Feature Flag/Gate
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>");
Reading a Dynamic Config
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>");
Getting an Layer/Experiment
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but we recommend the use of layers to enable quicker 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
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:
$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();
Learn more about identifying users, group analytics, and best practices for logging events in the logging events guide.
Retrieving Feature Gate Metadata
In certain scenarios, you may need more information about a gate evaluation than just a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object
Manual Exposures v3.4.0+
Manually logging exposures can be tricky and may lead to an imbalance in exposure events. For example, only triggering exposures for users in the Test group of an experiment will imbalance the experiment, making it useless.
Added in version 3.4.0, you can now query your gates/experiments without triggering an exposure as well as manually logging your exposures.
- Check Gate
- Get Config
- Get Experiment
- Get Layer
To check a gate without an exposure being logged, call the following.
$result = $this->statsig->checkGateWithExposureLoggingDisabled($user, 'a_gate_name');
Later, if you would like to expose this gate, you can call the following.
$this->statsig->manuallyLogGateExposure($user, 'a_gate_name');
To get a dynamic config without an exposure being logged, call the following.
$config = $this->statsig->getConfigWithExposureLoggingDisabled($user, 'a_dynamic_config_name');
Later, if you would like to expose the dynamic config, you can call the following.
$this->statsig->manuallyLogConfigExposure($user, 'a_dynamic_config_name');
To get an experiment without an exposure being logged, call the following.
$experiment = $this->statsig->getExperimentWithExposureLoggingDisabled($user, 'an_experiment_name');
Later, if you would like to expose the experiment, you can call the following.
$this->statsig->manuallyLogExperimentExposure($user, 'an_experiment_name');
To get a layer parameter without an exposure being logged, call the following.
$layer = $this->statsig->getLayerWithExposureLoggingDisabled($user, 'a_layer_name');
const paramValue = $layer->get('a_param_name', 'fallback_value');
Later, if you would like to expose the layer parameter, you can call the following.
$this->statsig->manuallyLogLayerParameterExposure($user, 'a_layer_name', 'a_param_name');
Cron Jobs
To keep your configurations up to date, and send event data to Statsig, you can create two jobs. Here, we document them as cron jobs, but you can use any out of band process to run them. If you are using Laravel, for example, 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 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
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 will use the Statsig LocalFileDataAdapter which writes to /tmp/statsig.configs
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 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 will use the Statsig LocalFileDataAdapter which writes to /tmp/statsig.logs
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 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 that while typing is lenient on the StatsigUser
object to allow you to pass in numbers, strings, arrays, objects, and potentially even enums or classes, the evaluation operators will only be able to operate on primitive types - mostly strings and numbers. While we attempt to smartly cast custom field types to match the operator, we cannot guarantee evaluation results for other types. For example, setting an array as a custom field will only ever be compared as a string - there is no operator to match a value in that array.
Private Attributes
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:
IDataAdapter
(required) - A class that implements IDataAdapter. Statsig provides the LocalFileDataAdapter, but you can write your own. See Data Stores.ILoggingAdapter
- A class that implements ILoggingAdapter. Statsig provides the LocalFileLoggingAdapter, but you can write your own. If no adapter is provided, logs will be sent during the request.
You can also configure:
- The environment (see using environments) via
setEnvironmentTier("production" | "staging" | "development" | <string>)
- The event queue size (How many events to track before they are sent to Statsig) via
setEventQueueSize(int $size)
.
Shutting Statsig Down
Because we batch and periodically flush events, some events may still be in memory when your app/server shuts down.
To make sure all logged events are properly flushed, you should tell Statsig to flush
when your app/server is closing:
$this->statsig->flush();
FAQ
How do I run experiments for logged out users?
See the guide on device level experiments
Can I use ID Lists with the PHP SDK?
Yes, since version 2.0.0
, ID Lists are now supported by the PHP SDK. Any SDK version less than v2.0.0 will not work with ID Lists.
Do I need the SDK, can I just use the HTTP API?
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.
Reference
Class: StatsigUser
class StatsigUser
{
static function withUserID(string $user_id): StatsigUser
static function withCustomIDs(array $custom_ids): StatsigUser
function setUserID(?string $user_id): StatsigUser
function setEmail(?string $email): StatsigUser
function setIP(?string $ip): StatsigUser
function setUserAgent(?string $user_agent): StatsigUser
function setLocale(?string $locale): StatsigUser
function setCountry(?string $country): StatsigUser
function setAppVersion(?string $app_version): StatsigUser
function setCustom(?array $custom): StatsigUser
function setPrivateAttributes(?array $private): StatsigUser
function setCustomIDs(?array $custom_ids): StatsigUser
}
Class: StatsigOptions
class StatsigOptions
{
function __construct(IDataAdapter $data_adapter, ?ILoggingAdapter $logging_adapter = null, ?IOutputLogger $output_logger = null)
function getConfigAdapter(): IConfigAdapter
function getLoggingAdapter(): ?ILoggingAdapter
/**
* Configure an output logger for additional debugging information
*/
function getOutputLogger(): ?IOutputLogger
function setEnvironmentTier(?string $tier)
/**
* @throws Exception - Given size cannot be less than 10 or greater than 1000
*/
function setEventQueueSize(int $size)
}
Interface: IDataAdapter
interface IDataAdapter
{
function get(string $key): ?string;
function set(string $key, ?string $value);
}
Interface: ILoggingAdapter
interface ILoggingAdapter
{
public function enqueueEvents(array $events);
public function getQueuedEvents(): array;
}