On this page

Experiment PHP SDK

Official documentation for Amplitude Experiment's server-side PHP SDK implementation.

Install

PHP version compatibility

The PHP Server SDK works with PHP 7.4+.

Install the PHP Server SDK with composer.

bash
composer require amplitude/experiment-php-server

Remote evaluation

The SDK supports and uses remote evaluation to fetch variants for users.

Quick start

  1. Initialize the experiment client
  2. Fetch variants for the user
  3. Access a flag's variant
php
<?php
// (1) Initialize the experiment client
$experiment = new \AmplitudeExperiment\Experiment();
$client = $experiment->initializeRemote('<DEPLOYMENT_KEY>');

// (2) Fetch variants for a user
$user = \AmplitudeExperiment\User::builder()
    ->deviceId('abcdefg')
    ->userId('user@company.com')
    ->userProperties(['premium' => true]) 
    ->build();
$variants = $client->fetch($user);

// (3) Access a flag's variant
$variant = $variants['FLAG_KEY'] ?? null;
if ($variant) {
    if ($variant->value == 'on') {
        // Flag is on
    } else {
        // Flag is off
    }
}

Initialize remote evaluation

Configure the SDK to initialize on server startup. The deployment key argument you pass into the apiKey parameter must live within the same project that you send analytics events to.

php
<?php
initializeRemote(string $apiKey, ?RemoteEvaluationConfig $config = null): RemoteEvaluationClient

Configuration

You can configure the SDK client on initialization.

EU data center

If you use Amplitude's EU data center, set the serverUrl option on initialization to https://api.lab.eu.amplitude.com

Fetch

Fetches variants for a user and returns the results. The function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.

php
<?php
fetch(User $user, ?FetchOptions $fetchOptions = null): array<Variant>
// An array of variants is returned on success, an empty array is returned on failure

FetchOptions

php
<?php
$user = \AmplitudeExperiment\User::builder()
    ->deviceId('abcdefg')
    ->userId('user@company.com')
    ->userProperties(['premium' => true])
    ->build();
$variants = $client->fetch($user);

After fetching variants for a user, you may want to access the variant for a specific flag.

php
<?php
$variant = $variants['FLAG-KEY'] ?? null;
if ($variant) {
    if ($variant->value == 'on') {
        // Flag is on
    } else {
        // Flag is off
    }
}

Local evaluation

Implements evaluation of variants for a user through local evaluation. If you plan to use local evaluation, you should understand the tradeoffs.

Quick start

  1. Initialize the local evaluation client.
  2. Fetch flag configs for the local evaluation client.
  3. Evaluate a user.
php
<?php
// (1) Initialize the experiment client
$experiment = new \AmplitudeExperiment\Experiment();
$client = $experiment->initializeLocal('<DEPLOYMENT_KEY>');

// (2) Fetch flags for the local evaluation client.
$client->refreshFlagConfigs();

// (3) Evaluate a user.
$user = \AmplitudeExperiment\User::builder()
    ->deviceId('abcdefg')
    ->userId('user@company.com')
    ->userProperties(['premium' => true]) 
    ->build();

$variants = $client->evaluate($user);

Initialize local evaluation

Refer to Local Evaluation.

Server deployment key

Initialize the local evaluation client with a server deployment key to access local evaluation flag configurations.

php
initializeLocal(string $apiKey, ?LocalEvaluationConfig $config = null): LocalEvaluationClient

Configuration

You can configure the SDK client on initialization.

EU data center

If you use Amplitude's EU data center, configure the serverUrl option on initialization to https://api.lab.eu.amplitude.com

refreshFlagConfigs

Fetch up-to-date local evaluation mode flag configs for evaluation.

php
refreshFlagConfigs(): void

Call refreshFlagConfigs() to ensure that flag configs are up-to-date before you use evaluate()

php
<?php
$client->refreshFlagConfigs();

getFlagConfigs

Return flag configs used in the client.

php
getFlagConfigs(): array

Use returned flag configs to reduce start up time by bootstrapping the local evaluation client.

php
<?php
$client->getFlagConfigs();

Evaluate

Executes the evaluation logic using the flags fetched on refreshFlagConfigs(). Give evaluate() a user object argument. Optionally pass an array of flag keys if you require only a specific subset of required flag variants.

Exposure tracking

Set exposureConfig to enable exposure tracking. Then, set tracksExposure to true in EvaluateOptions when calling evaluate().

php
evaluate(User $user, array $flagKeys = [], ?EvaluateOptions $options = null): array
php
<?php
// The user to evaluate
$user = \AmplitudeExperiment\User::builder()
        ->deviceId('abcdefg')
        ->build();

// Evaluate all flag variants
$allVariants = $client->evaluate($user);

// Evaluate a specific subset of flag variants
$specificVariants = $client->evaluate($user, [
  'my-local-flag-1',
  'my-local-flag-2',
]);

// Access a flag's variant
$variant = $allVariants['FLAG_KEY'] ?? null;
if ($variant) {
    if ($variant->value == 'on') {
        // Flag is on
    } else {
        // Flag is off
    }
}

EvaluateOptions

Assignment tracking

Deprecated. Use Exposure tracking instead.

You can configure the local evaluation client to send assignment events to Amplitude.

AssignmentTrackingProvider

The local evaluation client uses an assignment tracking provider to send assignment events to Amplitude. Amplitude provides a default assignment tracking provider, but this is best used for testing due to its synchronous nature. Amplitude recommends that you use a custom provider for increased flexibility and performance.

php
<?php
interface AssignmentTrackingProvider {
  public function track(Assignment $assignment): void;
}

The local evaluation client calls track() when it determines there are untracked assignment events. It compares the resulting assignment from evaluate() with the assignment cache and tracks it if it's not in the cache.

DefaultAssignmentTrackingProvider

The default assignment tracking provider is a basic implementation of the interface which uses the internal Amplitude package to send assignment events through synchronous HTTP requests.

php
<?php
class DefaultAssignmentTrackingProvider implements AssignmentTrackingProvider {
  public function __construct(Amplitude $amplitude);
}

Amplitude

AmplitudeConfig

php
<?php
$config = \AmplitudeExperiment\Amplitude\AmplitudeConfig::builder()
          ->useBatch(true)
          ->minIdLength(10)
          ->build();
$amplitude = new \AmplitudeExperiment\Amplitude\Amplitude('<API_Key>', $config);
$defaultAssignmentTrackingProvider = new \AmplitudeExperiment\Assignment\DefaultAssignmentTrackingProvider($amplitude);

Exposure tracking

You can configure the local evaluation client to send exposure events to Amplitude.

ExposureTrackingProvider

The local evaluation client uses an exposure tracking provider to send exposure events. Amplitude provides a default exposure tracking provider that tracks events to Amplitude. You can implement a custom provider to track events to other destinations or to customize the tracking behavior.

php
<?php
interface ExposureTrackingProvider {
  public function track(Exposure $exposure): void;
}

The local evaluation client calls track() when it determines there are untracked exposure events. It compares the resulting exposure from evaluate() with the exposure cache and tracks it if it's not in the cache.

DefaultExposureTrackingProvider

The default exposure tracking provider is an implementation of the ExposureTrackingProvider interface that sends exposure events to Amplitude using the internal Amplitude package through synchronous HTTP requests.

php
<?php
class DefaultExposureTrackingProvider implements ExposureTrackingProvider {
  public function __construct(Amplitude $amplitude);
}

Amplitude

AmplitudeConfig

php
<?php
$config = \AmplitudeExperiment\Amplitude\AmplitudeConfig::builder()
          ->useBatch(true)
          ->minIdLength(10)
          ->build();
$amplitude = new \AmplitudeExperiment\Amplitude\Amplitude('<API_Key>', $config);
$defaultExposureTrackingProvider = new \AmplitudeExperiment\Exposure\DefaultExposureTrackingProvider($amplitude);

Custom Logger

Configure local and remote evaluation clients to use a custom logger that implements the PSR logger interface. Otherwise, the SDK uses a default error_log-based logger.

Log level

The SDK uses the following log levels:

Custom HTTP Client

Configure local and remote evaluation clients to use a custom HTTP client that implements the HTTPClientInterface. Otherwise, the SDK uses a default Guzzle-based HTTP client.

HTTPClientInterface

GuzzleHTTPClient

Configure the default Guzzle client with the guzzleClientConfig option in RemoteEvaluationConfig and LocalEvaluationConfig.

php
<?php
// Configure the default Guzzle client
$config = \AmplitudeExperiment\RemoteEvaluationConfig::builder()
          ->guzzleClientConfig(['timeoutMillis' => 5000, 'retries' => 10])
          ->build();

Access Amplitude cookies

If you're using the Amplitude Analytics SDK on the client-side, the PHP server SDK provides an AmplitudeCookie class with convenience functions for parsing and interacting with the Amplitude identity cookie. The class ensures that the Device ID on the server matches the Device ID set on the client, especially if the client hasn't yet generated a Device ID.

php
<?php
use AmplitudeExperiment\AmplitudeCookie;

// Get the cookie name for the Amplitude API key
// For Browser SDK 2.0 cookies, use true as second parameter:
// $amp_cookie_name = AmplitudeCookie::cookieName('amplitude-api-key', true);
$amp_cookie_name = AmplitudeCookie::cookieName('amplitude-api-key');
$device_id = null;

// Try to get device ID from existing cookie
if (isset($_COOKIE[$amp_cookie_name])) {
  $cookie_data = AmplitudeCookie::parse($_COOKIE[$amp_cookie_name]);
  // For Browser SDK 2.0: AmplitudeCookie::parse($_COOKIE[$amp_cookie_name], true);
  $device_id = $cookie_data['deviceId'];
}

// If no device ID found, generate a new one and set the cookie
if ($device_id === null) {
  $device_id = uniqid('', true);
  $amp_cookie_value = AmplitudeCookie::generate($device_id);
  // For Browser SDK 2.0: AmplitudeCookie::generate($device_id, true);
  setcookie($amp_cookie_name, $amp_cookie_value, [
    'domain' => '.your-domain.com', // this should be the same domain used by the Amplitude JS SDK
    'httponly' => false,
    'secure' => false
  ]);
}

Was this helpful?