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.

1composer require amplitude/experiment-php-server

Remote evaluation

This 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
1<?php
2// (1) Initialize the experiment client
3$experiment = new \AmplitudeExperiment\Experiment();
4$client = $experiment->initializeRemote('<DEPLOYMENT_KEY>');
5 
6// (2) Fetch variants for a user
7$user = \AmplitudeExperiment\User::builder()
8 ->deviceId('abcdefg')
9 ->userId('user@company.com')
10 ->userProperties(['premium' => true])
11 ->build();
12$variants = $client->fetch($user);
13 
14// (3) Access a flag's variant
15$variant = $variants['FLAG_KEY'] ?? null;
16if ($variant) {
17 if ($variant->value == 'on') {
18 // Flag is on
19 } else {
20 // Flag is off
21 }
22}

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.

1<?php
2initializeRemote(string $apiKey, ?RemoteEvaluationConfig $config = null): RemoteEvaluationClient
Parameter Requirement Description
apiKey required The deployment key which authorizes fetch requests and determines which flags to evaluate for the user.
config optional The client configuration used to customize SDK client behavior.

Configuration

You can configure the SDK client on initialization.

Name
Description Default Value
serverUrl The host to fetch variants from. https://api.lab.amplitude.com
logger Set to use custom logger. If not set, a default logger is used. null
logLevel The log level to use for the logger. LogLevel::ERROR
httpClient The underlying HTTP client to use for requests, if this is not set, a default HTTP client will be used. null
guzzleClientConfig The configuration for the underlying default GuzzleHTTPClient (if used). defaults

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. This function remote evaluates the user for flags associated with the deployment used to initialize the SDK client.

1<?php
2fetch(User $user, array $flagKeys = []): array<Variant>
3// An array of variants is returned on success, an empty array is returned on failure
Parameter Requirement Description
user required The user to remote fetch variants for.
flagKeys optional Specific flags or experiments to evaluate. If empty, Amplitude evaluates all flags and experiments.
1<?php
2$user = \AmplitudeExperiment\User::builder()
3 ->deviceId('abcdefg')
4 ->userId('user@company.com')
5 ->userProperties(['premium' => true])
6 ->build();
7$variants = $client->fetch($user);

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

1<?php
2$variant = $variants['FLAG-KEY'] ?? null;
3if ($variant) {
4 if ($variant->value == 'on') {
5 // Flag is on
6 } else {
7 // Flag is off
8 }
9}

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.
1<?php
2// (1) Initialize the experiment client
3$experiment = new \AmplitudeExperiment\Experiment();
4$client = $experiment->initializeLocal('<DEPLOYMENT_KEY>');
5 
6// (2) Fetch flags for the local evaluation client.
7$client->refreshFlagConfigs();
8 
9// (3) Evaluate a user.
10$user = \AmplitudeExperiment\User::builder()
11 ->deviceId('abcdefg')
12 ->userId('user@company.com')
13 ->userProperties(['premium' => true])
14 ->build();
15 
16$variants = $client->evaluate($user);

Initialize local evaluation

For more information, see Local Evaluation.

Server deployment key

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

1initializeLocal(string $apiKey, ?LocalEvaluationConfig $config = null): LocalEvaluationClient
Parameter Requirement Description
apiKey required The server deployment key which authorizes fetch requests and determines which flags to evaluate for the user.
config optional The client configuration used to customize SDK client behavior.

Configuration

You can configure the SDK client on initialization.

Name
Description Default Value
serverUrl The host to fetch flag configurations from. https://api.lab.amplitude.com
logger Set to use custom logger. If not set, a default logger is used. null
logLevel The log level to use for the logger. LogLevel::ERROR
httpClient The underlying HTTP client to use for requests, if this is not set, a default HTTP client will be used. null
guzzleClientConfig The configuration for the underlying default GuzzleHTTPClient (if used). defaults
bootstrap Bootstrap the client with an array of flag key to flag configuration []
assignmentConfig Configuration for automatically tracking assignment events after an evaluation. null

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.

1refreshFlagConfigs(): void

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

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

getFlagConfigs

Return flag configs currently used in the client.

1getFlagConfigs(): array

Flag configs returned can be used to reduce start up time by bootstrapping the local evaluation client.

1<?php
2$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.

Automatic assignment tracking

Set assignmentConfig to automatically track an assignment event to Amplitude when you call evaluate().

1evaluate(User $user, array $flagKeys = []): array
Parameter Requirement Description
user required The user to evaluate.
flagKeys optional Specific flags or experiments to evaluate. If empty, Amplitude evaluates all flags and experiments.
1<?php
2// The user to evaluate
3$user = \AmplitudeExperiment\User::builder()
4 ->deviceId('abcdefg')
5 ->build();
6 
7// Evaluate all flag variants
8$allVariants = $client->evaluate($user);
9 
10// Evaluate a specific subset of flag variants
11$specificVariants = $client->evaluate($user, [
12 'my-local-flag-1',
13 'my-local-flag-2',
14]);
15 
16// Access a flag's variant
17$variant = $allVariants['FLAG_KEY'] ?? null;
18if ($variant) {
19 if ($variant->value == 'on') {
20 // Flag is on
21 } else {
22 // Flag is off
23 }
24}

Assignment tracking

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

Name
Description Default Value
assignmentTrackingProvider The AssignmentTrackingProvider used to send assignment events. required
cacheCapacity The maximum number of assignments stored in the assignment cache. 65536
apiKey The analytics API key. Not to be confused with the experiment deployment key. required
minIdLength The minimum length of userId and deviceId. 5

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.

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

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.

Parameter Requirement Description
assignment required The object representing an Experiment assignment event

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.

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

Amplitude

Name
Description Default Value
apiKey The analytics API key. Not to be confused with the experiment deployment key. required
config Configuration options null

AmplitudeConfig

Name
Description Default Value
flushQueueSize Events wait in the buffer and are sent in a batch. Experiment flushes the buffer when the number of events reaches the flushQueueSize. 200
minIdLength The minimum length of userId and deviceId. 5
serverZone The server zone of the projects. Supports EU and US. For EU data residency, Change to EU. US
serverUrl The API endpoint URL that events are sent to. Automatically selected by serverZone and useBatch. If this field is set with a string value instead of null, then serverZone and useBatch are ignored and the string value is used. https://api2.amplitude.com/2/httpapi
useBatch Whether to use batch API. By default, the SDK will use the default serverUrl. false
httpClient The underlying HTTP client to use for requests, if this is not set, a default HTTP client will be used. null
guzzleClientConfig The configuration for the underlying default GuzzleHTTPClient (if used). defaults
logger Set to use custom logger. If not set, a default logger is used. null
logLevel The log level to use for the logger. LogLevel::ERROR
1<?php
2$config = \AmplitudeExperiment\Amplitude\AmplitudeConfig::builder()
3 ->useBatch(true)
4 ->minIdLength(10)
5 ->build();
6$amplitude = new \AmplitudeExperiment\Amplitude\Amplitude('<API_Key>', $config);
7$defaultAssignmentTrackingProvider = new \AmplitudeExperiment\Assignment\DefaultAssignmentTrackingProvider($amplitude);

Custom Logger

Local and remote evaluation clients can be configured to use a custom logger which implements the PSR logger interface, otherwise a default error_log-based logger is used.

Log level

The following log levels are used by the SDK:

Level Description
NO_LOG Turn off logging
ERROR Error-level messages are logged
DEBUG Debug and error-level messages are logged

Custom HTTP Client

Local and remote evaluation clients can be configured to use a custom HTTP client which implements the HTTPClientInterface, otherwise a default Guzzle-based HTTP client is used.

HTTPClientInterface

Method Return Type Description
getClient Psr\HTTP\Client\ClientInterface Return the underlying PSR HTTP Client.
createRequest Psr\HTTP\Message\RequestInterface Return a PSR Request to be sent by the underlying PSR HTTP Client.

GuzzleHTTPClient

The default Guzzle client can be configured via the guzzleClientConfig option in RemoteEvaluationConfig and LocalEvaluationConfig.

Name
Description Default Value
timeoutMillis The timeout for requests in milliseconds. This timeout applies to the initial request, not subsequent retries. 10000
retries The number of retries to attempt if a request fails. 8
retryBackoffMinMillis The minimum (initial) backoff after a request fails. This delay scales according to the retryBackoffScalar setting. 500
retryBackoffMaxMillis The maximum backoff between retries. If the scaled backoff becomes greater than the maximum, Experiment uses the maximum for all subsequent requests. 10000
retryBackoffScalar Scales the minimum backoff exponentially. 1.5
retryTimeoutMillis The request timeout for retrying requests. 10000
1<?php
2// Configure the default Guzzle client
3$config = \AmplitudeExperiment\RemoteEvaluationConfig::builder()
4 ->guzzleClientConfig(['timeoutMillis' => 5000, 'retries' => 10])
5 ->build();

Access Amplitude cookies

If you use 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. This helps ensure 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.

1<?php
2// Grab amp device id if present
3$ampCookieName = AmplitudeCookie::cookieName('amplitude-api-key');
4$deviceId = null;
5 
6if (!empty($_COOKIE[$ampCookieName])) {
7 $parsedCookie = AmplitudeCookie::parse($_COOKIE[$ampCookieName]);
8 $deviceId = $parsedCookie['deviceId'];
9}
10 
11if ($deviceId === null) {
12 // deviceId doesn't exist, set the Amplitude Cookie
13 $deviceId = bin2hex(random_bytes(16));
14 $ampCookieValue = AmplitudeCookie::generate($deviceId);
15 setcookie($ampCookieName, $ampCookieValue, [
16 'domain' => '.your-domain.com', // this should be the same domain used by the Amplitude JS SDK
17 'httponly' => false,
18 'secure' => false,
19 ]);
20}
Was this page helpful?

Thanks for your feedback!

June 4th, 2024

Need help? Contact Support

Visit Amplitude.com

Have a look at the Amplitude Blog

Learn more at Amplitude Academy

© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.