• SDKS
No results for ""


PHP SDK reference

Read time: 7 minutes
Last edited: May 14, 2021

This reference guide documents all of the methods available in our PHP SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, read PHP SDK repository on GitHub. The online API docs contain the programmatic definitions of every type and method. Additionally you can clone and run a sample application using this SDK.

PHP 5.5 or higher.

Getting started

Building on top of our Getting Started guide, the following steps will get you started with using the LaunchDarkly SDK in your PHP application.

The first step is to install Composer and the LaunchDarkly SDK as a dependency in your application. Refer to the SDK releases page to identify the latest version if you want to depend on a specific version.

1php composer.phar require launchdarkly/server-sdk
3# Note that in earlier versions, this was "launchdarkly/launchdarkly-php"

Then require Composer's autoloader.

1require 'vendor/autoload.php';

Once the SDK is installed, you'll want to create a single, shared instance of LDClient. You should specify your SDK key here so that your application will be authorized to connect to LaunchDarkly and for your application and environment.

1$client = new LaunchDarkly\LDClient("YOUR_SDK_KEY");

Using $client, you can check which variation a particular user should receive for a given feature flag.

1$user = new LaunchDarkly\LDUser("user@test.com");
3if ($client->variation("your.flag.key", $user)) {
4 // application code to show the feature
5} else {
6 // the code to run if the feature is off

That's all!

You may remember from our Getting Started guide that users should be sure to shut down the LaunchDarkly client on application termination. This step does not exist in PHP because the PHP SDK does not maintain long-lived network connections nor an event queue.

Fetching Flags

There are two distinct methods of integrating LaunchDarkly in a PHP environment.

  • Guzzle Cache Middleware to request and cache HTTP responses in an in-memory array (default)

  • ld-relay to retrieve and store flags in Redis (recommended)

We strongly suggest using the ld-relay. Per-flag caching mode (Guzzle) is only intended for low-throughput environments.

Using Guzzle

Require Guzzle as a dependency:

1php composer.phar require "guzzlehttp/guzzle:6.2.1"
2php composer.phar require "kevinrob/guzzle-cache-middleware:1.4.1"

It will then be used as the default way of fetching flags.

With Guzzle, you could persist your cache somewhere other than the default in-memory store, like Memcached or Redis.

You could then specify your cache when initializing the client with the cache option.

1$client = new LaunchDarkly\LDClient("YOUR_SDK_KEY", array("cache" => $cacheStorage));

Using LD-Relay

Setup ld-relay in daemon-mode with Redis

Require Predis as a dependency:

1php composer.phar require "predis/predis:1.0.*"

Create the LDClient with the Redis feature requester as an option:

1$client = new LaunchDarkly\LDClient("your_sdk_key", ['feature_requester_class' => 'LaunchDarkly\LDDFeatureRequester', 'redis_host' => 'your.redis.host', 'redis_port' => 6379]);
Caching and PHP

PHP's shared-nothing architecture means that the out-of-the-box in-memory HTTP cache used by our SDK won't cache feature flags across requests. In production, we strongly recommend the ld-relay for PHP.

Customizing your client

In an earlier example, we passed a cache option as an array to the client constructor. There are a few additional options you can set in this array. Here's an example:

1$client = new LaunchDarkly\LDClient("YOUR_SDK_KEY", array("cache" => $cacheStorage, "connect_timeout" => 3));

We've set the client connect timeout to 3 seconds in addition to providing a custom cache storage provider. For a complete list of customizable parameters, read the documentation for the LDClient constructor.

Sending events in PHP

The LaunchDarkly SDK sends data back to our server to record events from Track and Variation calls. On our other platforms, this data is sent asynchronously, so that it adds no latency to serving web pages. PHP's shared-nothing architecture makes this difficult.

By default, LaunchDarkly forks an external process that executes curl to send this data. This is the most reliable way to send data without introducing latency to page load times. To use this method you must have the curl SSL certificate installed. To learn more, read SSL Certificate Verification.

If your server does not have curl installed, or has other restrictions that make it impossible to invoke curl as an external process, you may need to implement a custom EventProcessor to send events to LaunchDarkly.


Feature flag targeting and rollouts are all determined by the user you pass to your Variation calls. In our PHP SDK, we use a builder pattern to make it easy to construct users. Here's an example:

1$user = (new LDUserBuilder("aa0ceb"))->firstName("Ernestina")->lastName("Evans")->email("ernestina@example.com")->custom(["groups" => array("Google","Microsoft")])->build();

Let's walk through this snippet. The first argument to LDUserBuilder is the user's key. In this case we've used the hash "aa0ceb". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an email address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

All of the other attributes (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes.

Besides the key, LaunchDarkly supports the following attributes at the "top level". Remember, all of these are optional:

  • ip: Must be an IP address.
  • firstName: Must be a string. If you provide a first name, you can search for users on the Users page by name.
  • lastName: Must be a string. If you provide a last name, you can search for users on the Users page by name.
  • country: Must be a string representing the country associated with the user.
  • email: Must be a string representing the user's email address. If an avatar URL is not provided, we'll use Gravatar to try to display an avatar for the user on the Users page.
  • avatar: Must be an absolute URL to an avatar image for the user.
  • name: Must be a string. You can search for users on the User page by name
  • anonymous: Must be a boolean. See the section below on anonymous users for more details.

In addition to these, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

A note on types
Most of our built-in attributes (like names and email addresses) expect string values. Custom attributes values can be strings, booleans (like true or false), numbers, or lists of strings, booleans or numbers. If you enter a custom value on our dashboard that looks like a number or a boolean, it'll be interpreted that way. The PHP SDK is strongly typed, so be aware of this distinction.

Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us, including organizations, groups, andaccount plans. Anything you pass to us becomes available instantly on our dashboard.

Private user attributes

You can optionally configure the PHP SDK to treat some or all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

In the PHP SDK there are two ways to define private attributes for the entire LaunchDarkly client:

In the LaunchDarkly config, you can set allAttributesPrivate to true. If this is enabled, all user attributes (except the key) for all users are removed before the user is sent to LaunchDarkly. In the LaunchDarkly config object, you can define a list of privateAttributeNames. If any user has a custom or built-in attribute named in this list, it will be removed before the user is sent to LaunchDarkly.

You can also mark attributes as private when building the user object itself by calling the equivalent "private" LDUserBuilder method. For example:

1$user = (new LDUserBuilder('aa0ceb'))
2 ->privateEmail('test@example.com')
3 ->build();

When this user is sent back to LaunchDarkly, the email attribute will be removed.

Anonymous users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

1$user = (new LDUserBuilder("aa0ceb"))->anonymous(true)->build();

You will still need to generate a unique key for anonymous users. Session IDs or UUIDs work best for this.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. You also can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. This is actually a good thing, because it keeps anonymous users from polluting your Users page!

Aliased users

There are situations in which multiple LaunchDarkly users can represent one person. For example, this can happen when a person initially logs into an application. The person might be represented by an anonymous user before they log in, and a different user after they log in. In that case, that one person would be identified by two different users as denoted by different user keys.

The SDK can associate these two LaunchDarkly users by sending an alias event. You can manually tell the SDK to send an alias event with the alias function.

1$client->alias($user, $previousUser);


The variation method determines which variation of a feature flag a user receives.

1$value = $client->variation($key, $user, false);

variation calls take the feature flag key, an LDUser, and a default value.

The default value will only be returned if an error is encountered. For example, the default value returns if the feature flag key doesn't exist or the user doesn't have a key specified.

The variation call will automatically create a user in LaunchDarkly if a user with that user key doesn't exist already. There's no need to create users ahead of time (but if you do need to, take a look at Identify).


The variationDetail method allows you to evaluate a feature flag (using the same parameters as you would for variation) and receive more information about how the value was calculated.

The variation detail is returned in an object that contains both the result value and a "reason" object which will tell you, for instance, if the user was individually targeted for the flag or was matched by one of the flag's rules. It will also indicate if the flag returned the default value due to an error. You can examine the "reason" data programmatically; you can also view it with Data Export, if you are capturing detailed analytics events for this flag.

To learn more, read Evaluation reasons.


The track method allows you to record actions your users take on your site. This lets you record events that take place on your server. In LaunchDarkly, you can tie these events to goals in A/B tests. Here's a simple example:

1$client->track("your-goal-key", user);

You can also attach custom data (anything that can be marshaled to JSON) to your event by passing an extra parameter to track:

1$client->track("Completed purchase", user, ["price" => 320]);


The identify method creates or updates users on LaunchDarkly, making them available for targeting and autocomplete on the dashboard. In most cases, you won't need to call identify. The variation call will automatically create users on the dashboard for you. identify can be useful if you want to pre-populate your dashboard before launching any features.


All flags

Creating users

Unlike variation and identify calls, allFlagsState does not send events to LaunchDarkly. Users are not created or updated in the LaunchDarkly dashboard.

The allFlagsState method captures the state of all feature flag keys with regard to a specific user. This includes their values, as well as other metadata.

This method can be useful for passing feature flags to your front-end. In particular, it can be used to provide bootstrap flag settings for our JavaScript SDK.

1$state = $client->allFlagsState($user);

Secure mode hash

The secureModeHash method computes an HMAC signature of a user signed with the client's SDK key. If you're using our JavaScript SDK for client-side flags, this method generates the signature you need for secure mode.


Offline mode

In some situations, you might want to stop making remote calls to LaunchDarkly and fall back to default values for your feature flags. For example, if your software is both cloud-hosted and distributed to customers to run on premise, it might make sense to fall back to defaults when running on premise. setOffline lets you do this easily.

1$client = new LaunchDarkly\LDClient("YOUR_SDK_KEY", array("offline" => true));
2$client->variation("any.feature.flag", user, false); // will always return the default value (false)


The PHP SDK uses Monolog. All loggers are namespaced under LaunchDarkly. A custom logger may be passed to the SDK by the configurable logger property:

1$client = new LaunchDarkly\LDClient("YOUR_SDK_KEY", array("logger" => new Logger("LaunchDarkly", [new ErrorLogHandler(0, Logger::DEBUG)])));

Be aware of two considerations when enabling the DEBUG log level:

  1. Debug-level logs can be very verbose. It is not recommended that you turn on debug logging in high-volume environments.
  2. Potentially sensitive information is logged including LaunchDarkly users created by you in your usage of this SDK.