Setup the SDK
1
Install the SDK
Installation
1. Install and Add as a Dependency
You can install the new PHP Core SDK using composer:2. PHP Configuration Requirements
The PHP Core SDK uses the FFI extension to interface with the Rust core. You must enable FFI in your PHP configuration by settingffi.enable=true
in your php.ini file.For more information about this setting, see the PHP manual for ffi.enable.3. Add Scripts & Cron Job
Add post-install and post-update scripts in composer.json:2
Initialize the SDK
After installation, you will need to initialize the SDK using a Server Secret Key from the Statsig console.There is also an optional parameter named
Server Secret Keys should always be kept private. If you expose one, you can disable and recreate it in the Statsig console.
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: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 Jobinitialize
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 (thinkreturn 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:
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 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:Getting a Layer/Experiment
Then we have Layers/Experiments, which you can use to run A/B/n experiments. We offer two APIs, but often recommend the use of layers, which make parameters reusable and let you run mutually exclusive experiments.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:Parameter Stores
Sometimes you don’t know whether you want a value to be a Feature Gate, Experiment, or Dynamic Config yet. If you want on-the-fly control of that outside of your deployment cycle, you can use Parameter Stores to define a parameter that can be changed into at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application can prove very useful for future flexibility and can even allow non-technical Statsig users to turn parameters into experiments. 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:Sending Events to Log Explorer
You can forward logs to Logs Explorer for convenient analysis using the Forward Log Line Event API. This lets you include custom metadata and event values with each log. Sending events to Log Explorer is not yet available for this sdk. Need it now? Let us know in Slack.Using Shared Instance
In some applications, you may want to create a single Statsig instance that can be accessed globally throughout your codebase. The shared instance functionality provides a singleton pattern for this purpose:Statsig User
TheStatsigUser
object represents a user in Statsig. You must provide a userID
or at least one of the customIDs
to identify the 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.
Private Attributes
Private attributes are user attributes that are used for evaluation but are not forwarded to any integrations. They are useful for PII or sensitive data that you don’t want to send to third-party services.Private Attributes
You can define which attributes are considered “private” and should not be forwarded to any third-party integrations like the data connectors by setting theprivateAttributes
parameter in the StatsigUser
constructor. The privateAttributes
parameter is a key-value dictionary where keys are attribute names and values are the private values. Note that in the example user object above, for the key "email"
, we have values for the top-level email
field AND for the private attributes field with "email"
as the key. These are distinct; you can have a value in the top-level email
field that is not private
, and a value in private_attributes
that is private
, or vice versa.
Statsig Options
You can pass in an optional parameteroptions
in addition to sdkKey
during initialization to customize the Statsig client. Here are the available options that you can configure.
StatsigOptions
StatsigOptions
Custom URL for fetching feature specifications.
Custom URL for logging events.
An adapter with custom storage behavior for config specs. For example, use
StatsigLocalFileSpecsAdapter
to store configs in the local filesystem.An adapter with custom event logging behavior. For example, use
StatsigLocalFileEventLoggingAdapter
to store events in the local filesystem.Environment parameter for evaluation.
How often events are flushed to Statsig servers (in milliseconds).
Maximum number of events to queue before forcing a flush.
How often the SDK updates specifications from Statsig servers (in milliseconds).
Controls the verbosity of SDK logs.
Disables country lookup based on IP address. Set to
true
to improve performance if country-based targeting is not needed.Disables user agent parsing. Set to
true
to improve performance if device/browser-based targeting is not needed.Maximum time in milliseconds to wait for SDK initialization to complete. If initialization takes longer than this timeout, the SDK will continue to operate but may return default values until initialization completes.
When set to true, the SDK will fallback to using the Statsig API directly if custom adapters (like local file adapters) fail to load configurations.
Enable/disable ID list functionality. Required to be
true
when using segments with more than 1000 IDs. See ID List segments for more details.Performance Recommendations
If you are experiencing performance issues, particularly with long initialization times, you can disable user agent parsing and country lookup to improve performance:- Set
disable_user_agent_parsing: true
if you don’t need device or browser-based targeting - Set
disable_country_lookup: true
if you don’t need country-based targeting
Example Usage
When using
StatsigLocalFile
Adapters, ensure your cron job has run at least one time before using Statsig.
See Add Scripts & Cron JobCustom Adapters
SpecsAdapterBase - Custom Configuration Sources
TheSpecsAdapterBase
allows you to fetch Statsig configurations from custom sources instead of (or in addition to) Statsig’s servers. This is useful when you want to:
- Store configurations in your own database or cache (e.g., Redis, Memcached)
- Implement custom caching strategies
- Use Statsig in environments with restricted network access
- Reduce latency by serving configs from a local source
Implementation
To create a custom specs adapter, extend theSpecsAdapterBase
class and implement the required methods:
Usage
Key Methods
setup(SpecsUpdateListener $listener)
: Called during initialization to provide the listener for spec updatesstart()
: Called when the SDK starts. Fetch and provide initial configuration specsshutdown()
: Called when the SDK shuts down. Clean up resourcesscheduleBackgroundSync()
: Called to schedule periodic updates of configuration specs
SpecsUpdateListener
provides:
didReceiveSpecsUpdate(string $specs, string $source, int $timestamp)
: Notify the SDK of new specsgetCurrentSpecsInfo()
: Get information about current specs
EventLoggingAdapterBase - Custom Event Destinations
TheEventLoggingAdapterBase
allows you to send events to custom destinations instead of or in addition to Statsig’s servers. This is useful when you want to:
- Send events to your existing analytics platform
- Store events in a database for custom analysis
- Forward events to multiple destinations
- Implement custom batching or retry logic
Implementation
To create a custom event logging adapter, extend theEventLoggingAdapterBase
class and implement the required methods:
Usage
Key Methods
start()
: Called when the SDK starts. Initialize connections or resourceslogEvents(LogEventRequest $request): bool
: Process and send events. Return true on success, false on failureshutdown()
: Called when the SDK shuts down. Clean up resources
LogEventRequest
contains:
event_count
: Number of events in the requestretries
: Number of retry attempts for this requestpayload
:LogEventPayload
with events and metadata
LogEventPayload
contains:
events
: Array of event objects with user data, event names, and metadatastatsig_metadata
: SDK metadata including version and environment information
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 callshutdown()
before your app/server shuts down:
Persistent Storage
The Persistent Storage interface allows you to implement custom storage for user-specific configurations. This enables you to persist user assignments across sessions, ensuring consistent experiment groups even when the user returns later. This is particularly useful for client-side A/B testing where you want to ensure users always see the same variant.Persistent Storage
The Persistent Storage interface allows you to implement custom storage for experiment assignments. This ensures consistent user experiences across sessions by persisting experiment assignments. For more information on persistent assignments, see the Persistent Assignment documentation.Not supported at this time.
Data Store
The Data Store interface allows you to implement custom storage for Statsig configurations. This enables advanced caching strategies and integration with your preferred storage systems.Data Store
The Data Store interface allows you to implement custom storage for Statsig configurations. This enables advanced caching strategies and integration with your preferred storage systems.Not supported at this time.
Custom Output Logger
The Output Logger interface allows you to customize how the SDK logs messages. This enables integration with your own logging system and control over log verbosity.Custom Output Logger
The Output Logger interface allows you to customize how the SDK logs messages. This enables integration with your own logging system and control over log verbosity.Not supported at this time.
Observability Client
The Observability Client interface allows you to monitor the health of the SDK by integrating with your own observability systems. This enables tracking metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, see the Monitoring documentation.Observability Client
The Observability Client interface allows you to monitor the health of the SDK by integrating with your own observability systems. This enables tracking metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, see the Monitoring documentation.Not supported at this time.
Notes on Beta Version
The PHP SDK expects an adapter to be provided for both logging and saving config specs, given the stateless nature of PHP. In our example, we’ve provided simple file-based adapters. More mature implementations may choose a different, and more performant caching approach. If you need help setting this up, reach out to us in Slack.FAQ
How do I run experiments for logged out users?
How do I run experiments for logged out users?
See the guide on device level experiments