# PHP Server SDK

## Getting Started​

The following will outline how to get up and running with Statsig for PHP.

### Create an Account​

To work with the SDK, you will need a Statsig account. If you don't yet have an account, you can sign up for a free one here. You could skip this for now, but you will need an SDK key and some gates/experiments to use with the SDK in just a minute.

### 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.

### 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 exposed it, you can create a new one in 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.

require_once __DIR__ . '/vendor/autoload.php'; // path to installation folderuse 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 cron job 🔥​ ##### caution If you do not configure a cron job, your request performance may be impacted. A check for configuration freshness is made before evaluation (checkGate/getConfig/getExperiment). If your configurations are over 1 minute old, a network request will be fired to Statsig to update them. See Cron Jobs ## Working with the SDK​ ### Checking a 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) ##### Asynchronous APIs We mentioned earlier that after calling initialize most SDK APIs would run synchronously, so why are getConfig and checkGate asynchronous? The main reason is that older versions of the SDK might not know how to interpret new types of gate conditions. In such cases the SDK will make an asynchronous call to our servers to fetch the result of a check. This can be resolved by upgrading the SDK, and we will warn you if this happens. For more details, read our blog post about SDK evaluations. If you have any questions, please ask them in our Feedback Repository. ### 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:

## 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(IConfigAdapter$config_adapter, ?ILoggingAdapter $logging_adapter = null) function getConfigAdapter(): IConfigAdapter function getLoggingAdapter(): ?ILoggingAdapter 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{    public function enqueueEvents(array \$events);    public function getQueuedEvents(): array;}