Skip to main content

PHP Server SDK

Installation

1. Install and Add as a Dependency

You can install the new PHP Core SDK using composer:

composer require statsig/statsig-php-core

2. Add Scripts & Cron Job

Add post-install and post-update scripts in composer.json:

// composer.json
{
"name": "awesome-php-project",
...
"scripts": {
...
"post-install-cmd": [
"cd vendor/statsig/statsig-php-core && php post-install.php"
],
"post-update-cmd": [
"cd vendor/statsig/statsig-php-core && php post-install.php"
]
}
}

Next, you'll want to add a script to sync your Statsig configs and flush your events, see example files on Statsig's Github here.

You'll also want to setup cron jobs to run these scripts periodically:

*/10 * * * * /usr/bin/php /var/www/example.com/bin/StatsigSyncConfig.php 1>> /dev/null 2>&1
*/1 * * * * /usr/bin/php /var/www/example.com/bin/StatsigFlushEvents.php 1>> /dev/null 2>&1

Also, be sure to run the StatsigSyncConfig.php cron job at least once before proceeding.

Initialize the SDK

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

info

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 an optional parameter named options that allows you to pass in a StatsigOptions to customize the SDK.

You'll want to add your client secret key to the environment, by adding to a .env file, or directly on the command line:

export STATSIG_SECRET_KEY=secret-123456789
// At the top of your file
use Statsig\Statsig;
use Statsig\StatsigOptions;
use Statsig\StatsigLocalFileEventLoggingAdapter;
use Statsig\StatsigLocalFileSpecsAdapter;

//In the case of slim framework, in container builder definitions:

Statsig::class => function (ContainerInterface $c) {
$sdk_key = getenv("STATSIG_SECRET_KEY");

$options = new StatsigOptions(
null,
null,
new StatsigLocalFileSpecsAdapter($sdk_key, "/tmp"),
new StatsigLocalFileEventLoggingAdapter($sdk_key, "/tmp")
);

$statsig = new Statsig($sdk_key, $options);
$statsig->initialize();
return $statsig;
},
caution

StatsigLocalFile Adapters rely on cron jobs and files. If you are seeing errors around file access, ensure your cron job has run at least one time before using Statsig. See Add Scripts & Cron Job

initialize will perform a network request. After initialize completes, virtually all SDK operations will be synchronous (See Evaluating Feature Gates in the Statsig SDK). The SDK will fetch updates from Statsig in the background, independently of your API calls.

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\Statsig;
use Statsig\StatsigUserBuilder;

$user = StatsigUserBuilder::withUserID('my_user')->build();
$passed = $statsig->checkGate($user, 'my_gate');

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:

$user = StatsigUserBuilder::withUserID('my_user')->build();
$config = $statsig->getDynamicConfig($user, 'my_config');

Getting a 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.

$user = StatsigUserBuilder::withUserID('my_user')->build();
$xp = $statsig->getExperiment($user, 'an_experiment');

Parameter Stores

Parameter stores are not yet available for this sdk. Need it now? Let us know in Slack.

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:

$user = StatsigUserBuilder::withUserID('my_user')->build();
$statsig->logEvent($user, 'an_experiment');

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:

FeatureGate gate = statsig.getFeatureGate(user, "exmaple_gate");

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. At least one ID (userID or customID) is required because it's needed to provide a consistent experience for a given user (click here)

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

Previous Statsig SDKs enabled country and user agent parsing by default, but our new class of SDKs require you to opt-in by setting StatsigOptions.enable_country_lookup and StatsigOptions.enable_user_agent_parsing. Providing parsed fields yourself is often advantageous for consistency and speed.

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 Class

The StatsigOptions class is used to specify optional parameters when initializing the Statsig client.

Parameters

  • specs_url: Custom URL for fetching feature specifications.

  • log_event_url: Custom URL for logging events.

  • specs_adapter: An adapter with custom storage behavior for config specs.

    For example, use StatsigLocalFileSpecsAdapter to store configs in the local filesystem.

  • event_logging_adapter: An adapter with custom event logging behavior.

    For example, use StatsigLocalFileEventLoggingAdapter to store events in the local filesystem.

  • environment: Environment parameter for evaluation.

  • event_logging_flush_interval_ms: How often events are flushed to Statsig servers (in milliseconds).

  • event_logging_max_queue_size: Maximum number of events to queue before forcing a flush.

  • specs_sync_interval_ms: How often the SDK updates specifications from Statsig servers (in milliseconds).

  • output_log_level: Controls the verbosity of SDK logs.


Example Usage

use Statsig\Statsig;
use Statsig\StatsigOptions;
use Statsig\StatsigLocalFileSpecsAdapter;
use Statsig\StatsigLocalFileEventLoggingAdapter;

// Initialize StatsigOptions with custom parameters
$options = new StatsigOptions(
null, // specs_url
null, // log_event_url
new StatsigLocalFileSpecsAdapter($sdk_key, "/tmp"), // specs_adapter
new StatsigLocalFileEventLoggingAdapter($sdk_key, "/tmp"), // event_logging_adapter
"development", // environment
60000, // event_logging_flush_interval_ms
1000, // event_logging_max_queue_size
600000, // specs_sync_interval_ms
"INFO" // output_log_level
);

// Pass the options object into Statsig constructor
$statsig = new Statsig($sdk_key, $options);
$statsig->initialize();
caution

When using StatsigLocalFile Adapters, ensure your cron job has run at least one time before using Statsig. See Add Scripts & Cron Job

Shutting Statsig Down

Because we batch and periodically flush events, some events may not have been sent when your app/server shuts down.

To make sure all logged events are properly flushed, you should tell Statsig to shutdown when your app/server is closing:

// Method signature
public function shutdown(): void

// example usage
try {
$statsig->shutdown();
echo "Statsig instance has been successfully shutdown.\n";
} catch (Exception $e) {
error_log($e->getMessage());
}
Alternatively, if you are operating in a serverless environment/cloud function, you may wish to leave Statsig running in case your function is recycled but flush the logs to Statsig servers. Or, if you need an async method to wait for logs to post before resolving, you can use:
// Method signature
public function flushEvents(): void

// example usage
try {
$statsig->flushEvents();
echo "All events have been successfully flushed.\n";
} catch (Exception $e) {
echo "Failed to flush events: " . $e->getMessage() . "\n";
}