> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PHP SDK

> Integrate the Kameleoon PHP SDK to run experiments and activate feature flags on PHP back-end servers, with optional cron job tracking.

With the PHP SDK, you can run experiments and activate feature flags on your back-end PHP server. Integrating our SDK into your web-application is easy, and its footprint ( memory and network usage) is low.

**Getting started**: For help getting started, see the [Developer guide](#developer-guide).

**Changelog**: Latest version of the PHP SDK: 4.23.0 [Changelog](https://github.com/Kameleoon/client-php/blob/master/CHANGELOG.md).

**SDK methods**: For the full reference documentation of the PHP SDK, see the [reference](#reference) section.

## Developer guide

This guide is designed to help you integrate our SDK into your application code.

### Getting started

You should first install our SDK. Once uncompressed, you will see two directories: **kameleoon/** and **job/**.

#### Installing the PHP client (Composer package)

<Warning>
  Please carefully read the sections on [installing the cron job](#installing-the-cron-job) and [using the PHP SDK without a cron job](#using-the-php-sdk-without-a-cron-job).
</Warning>

The installation package is available on [Packagist](https://packagist.org/packages/kameleoon/kameleoon-client-php). You can install the PHP SDK by adding it as a dependency using Composer:

```json title="composer.json" theme={null}
{
  "require": {
    "kameleoon/kameleoon-client-php": "^4.18.0"
  }
}
```

Finally, execute the following command to regenerate the autoloader:

```bash theme={null}
composer install
```

#### With a cron job (Recommended)

<Tip>
  Setting up the cron allows the tracking of data added by the PHP sdk with the [addData()](#adddata) method. However, if you are unable to install it, front end tracking can still be implemented following [this guide](#without-a-cron-job).
</Tip>

The **job/** directory corresponds to a job that must be executed via a standard job scheduler (like cron).
We suggest installing the script at `/usr/local/opt/kameleoon/kameleoon-client-php-process-queries.sh` and using our default supplied crontab entry. However, you can install it in another location and modify the crontab entry accordingly.

##### Without a cron job

If you cannot install the cron job, you can use Kameleoon in [hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation) to benefit from the Kameleoon Application Engine's, `engine.js` (previously named, `kameleoon.js`) tracking capabilities. Our SDK provides the [`getEngineTrackingCode()`](#getenginetrackingcode) method, which sends exposure events to Kameleoon or any other analytics solution you use on your website.

<Warning>
  With this approach **you won't be able to track data** added with the [addData()](#adddata) method of the PHP SDK.
  In other words, the **only** way for the PHP SDK to collect and process experiment data server-side is through the **cron job**.
  The hybrid mode is useful for tracking purposes, but **does not enable backend data collection**.
</Warning>

#### Additional configuration

You can customize the behavior of the PHP SDK via a configuration file. We provide a sample configuration file named `client-php.json.sample` in the SDK archive. You can also [download a sample configuration](/assets/developer-docs/sdks/web-sdks/client-configs/client-php.json) file. We suggest to install this file to the default path of `/tmp/kameleoon/client-php.json`. The following table shows the available properties that you can set:

| Key                                                                                                         | Description                                                                                                                                                                                                                                                                                                                                                                 | Default value                |
| ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
| `clientId` / `client_id` <Badge color="red" size="sm">required</Badge>                                      | Required for authentication to the Kameleoon service. To find your `client_id`, see the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) documentation.                                                                                                                                                                          |                              |
| `clientSecret` / `client_secret` <Badge color="red" size="sm">required</Badge>                              | Required for authentication to the Kameleoon service. To find your `client_secret`, see the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) documentation.                                                                                                                                                                      |                              |
| `kameleoonWorkDir` / `kameleoon_work_dir` <Badge color="green" size="sm">optional</Badge>                   | Specifies a working directory for the PHP client (which will create files in this directory). The directory needs to be writable by the PHP user.                                                                                                                                                                                                                           | `/tmp/kameleoon/client-php/` |
| `refreshIntervalMinute` / `refresh_interval_minute` <Badge color="green" size="sm">optional</Badge>         | Specifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers.                                                                | `60` minutes                 |
| `defaultTimeoutMillisecond` / `default_timeout_millisecond` <Badge color="green" size="sm">optional</Badge> | Specifies the timeout, in milliseconds, for network requests from the SDK. Set the value to `30` seconds or more if you do not have a stable connection. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value. | `10000` milliseconds         |
| `cookieOptions->topLevelDomain` / `cookie_options.domain` *(required in hybrid mode)*                       | The current top-level domain for your website . Use the format: `example.com`. Don't include `https://`, `www`, or other subdomains. Kameleoon uses this information to set the corresponding cookie on the top-level domain.                                                                                                                                               | `null`                       |
| `cookieOptions->secure` / `cookie_options.secure` <Badge color="green" size="sm">optional</Badge>           | Controls the **Secure** cookie attribute.                                                                                                                                                                                                                                                                                                                                   | `false`                      |
| `cookieOptions->httpOnly` / `cookie_options.http_only` <Badge color="green" size="sm">optional</Badge>      | Controls the **HttpOnly** cookie attribute.                                                                                                                                                                                                                                                                                                                                 | `false`                      |
| `cookieOptions->sameSite` / `cookie_options.samesite` <Badge color="green" size="sm">optional</Badge>       | Controls the **SameSite** cookie attribute.                                                                                                                                                                                                                                                                                                                                 | `Lax`                        |
| `environment` / `environment` <Badge color="green" size="sm">optional</Badge>                               | Environment from which the feature flag’s configuration is to be used. The value can be `production`, `staging`, `development`. See the [managing environments](/user-manual/experimentation/feature-experimentation/configure-your-feature-flags/manage-environments) article for details.                                                                                 | `production`                 |
| `networkDomain` / `network_domain` <Badge color="green" size="sm">optional</Badge>                          | Custom domain used by SDKs for outgoing requests, often for proxying. Must be a valid domain (e.g., example.com or sub.example.com). Invalid formats default to Kameleoon's value.                                                                                                                                                                                          | `null`                       |
| `requestBodySizeLimitBytes` / `request_body_size_limit_bytes` *(optional)*                                  | Limits the size of tracking packages (in bytes) — files that store data collected between cron job runs. In some cases, reducing the package size may be necessary due to server or network restrictions. The maximum allowed value is 2.5 MB (`2621440` bytes).                                                                                                            | `2621440`                    |
| `debugMode` / `debug_mode` *(deprecated)*                                                                   | The parameter sends additional information to our tracking servers to help analyze issues. It should usually be off (**false**), but activating it (**true**) has no impact on SDK performance. This field is deprecated and will be removed in SDK version `5.0.0`. Use [`KameleoonLogger::setLogLevel`](#log-levels) instead.                                             | `false`                      |

<Note>
  If you do not use the default path (`/tmp/kameleoon/client-php.json`) for the configuration file, you will need to:

  * pass your configuration file's path as a third argument to the `KameleoonClientFactory::create()` method;
  * modify your crontab entry to add the --conf argument to the job script (so, for instance, it would be `bash /usr/local/opt/bin/kameleoon-client-php-process-queries.sh --conf /my/path/kameleoon.json`).
</Note>

<Note>
  To learn more about `client_id` and `client_secret`, and how to obtain them, refer to the [API credentials](/user-manual/account-and-team-management/users-and-teams/api-credentials) article. Note that the Kameleoon PHP SDK uses the Automation API and follows the OAuth 2.0 client credentials flow.
</Note>

#### Initializing the Kameleoon client

After installing the SDK into your application and configuring the correct credentials (in `/tmp/kameleoon/client-php.json`), the next step is to create the Kameleoon client in your application code. For example:

```php theme={null}
require "vendor/autoload.php";

use Kameleoon\KameleoonClientConfig;
use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;

$siteCode = "a8st4f59bj";

try {
    // Read from default configuration path: "/tmp/kameleoon/php-client/"
    $kameleoonClient = KameleoonClientFactory::create($siteCode);
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}

try {
    $kameleoonClient = KameleoonClientFactory::create($siteCode, "custom/file/path/client-php.json");
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}

try {
    $cookieOptions = KameleoonClientConfig::createCookieOptions(
        "example.com", // domain: optional, but strictly recommended
        false, // secure: optional (false by default)
        false, // httponly: optional (false by default)
        "Lax" // samesite: optional (Lax by default)
    );
    $config = new KameleoonClientConfig(
        "<clientId>", // clientId: mandatory
        "<clientSecret>", // clientSecret: mandatory
        "/tmp/kameleoon/php-client/", // kameleoonWorkDir: optional / ("/tmp/kameleoon/php-client/" by default)
        60, // refreshIntervalMinute: in minutes, optional (60 minutes by default)
        10_000, // defaultTimeoutMillisecond: in milliseconds, optional (10_000 ms by default)
        false, // debugMode: optional (false by default)
        $cookieOptions, // cookieOptions: optional
        "development", // environment: optional ("production" by default)
        "example.com", // networkDomain: optional (null by default)
        1024*1024, // requestBodySizeLimitBytes: optional (2560 * 1024 by default)
    );
    $kameleoonClient = KameleoonClientFactory::createWithConfig($siteCode, $config);
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
```

A KameleoonClient is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you need to run an experiment. Note that the SDK takes its settings from a [configuration file.](#additional-configuration) By default, the path `/tmp/kameleoon/client-php.json` will be used, but you can use a different path for the configuration file by providing an optional third argument to the `KameleoonClientFactory::create()` method.

<Note>
  It's your responsibility as the application developer to use correct logic in your application code within the context of A/B testing via Kameleoon. A good practice is to always assume that the current visitor can be left out of the experiment because the experiment has not yet been launched. Leaving out the current visitor is simple, as it corresponds to the implementation of the default / reference variation logic. The code samples in the next paragraph show examples of such an approach.
</Note>

#### Activating a feature flag

##### Assigning a unique ID to a user

To assign a unique ID to a user, you can use the [`getVisitorCode()`](#getvisitorcode) method. If a **visitor code** doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a `defaultVisitorCode` that you would have generated. The ID is then set in a response headers cookie.

If you are using Kameleoon in [Hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation), calling the `getVisitorCode()` method ensures that the unique ID (**visitor code**) is shared between the application file `engine.js` (previously named, `kameleoon.js`) and the SDK.

##### Retrieving a flag configuration

To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account.

To determine the status or variation of a feature flag for a specific user, you should use the [`getVariation()`](#getvariation) or [`isFeatureActive()`](#isfeatureactive) method to retrieve the configuration based on the `featureKey`.

The `getVariation()` method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the `featureKey` and `visitorCode`.

The `isFeatureActive()` method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.

If your feature flag has associated variables (such as specific behaviors tied to each variation) `getVariation()` also enables you to access the [`Variation`](#variation) object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When `track=true`, the SDK will send the exposure event to the specified experiment on one of the next tracking request, which is automatically performed by the cron job. By default, its interval is 1 minute.

The `getVariation()` method allows you to control whether tracking is done. If `track=false`, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting `track=false` is helpful when using the `getVariations()` method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view [this article](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics)

##### Adding data points to target a user or filter / breakdown visits in reports

To target a user, ensure you've added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the [`addData()`](#adddata) method to add these data points to the user's profile.

To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the [`getRemoteVisitorData()`](#getremotevisitordata) method. This method asynchronously fetches data from the servers. It is important to call `getRemoteVisitorData()` *before* retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.

To learn more about available targeting conditions, see the [detailed article on the subject](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list [here](/user-manual/experiment-analytics/analyze-results/results-page-settings#breakdown-audience).

If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's [Custom Data feature](#customdata). Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the [`flush()`](#flush) method to send the collected data to Kameleoon servers for analysis.

<Note>
  To ensure your results are accurate, it's recommended to filter out bots by using the [`UserAgent`](#useragent) data type.
</Note>

##### Tracking goal conversions

When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use the [`trackConversion()`](#trackconversion) method and provide the required `visitorCode` and `goalId` parameters.

The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined in the interval tracking crontab). If you prefer to send the request immediately, use the [`flush()`](#flush) method with the parameter `instant=true`.

##### Sending events to analytics solutions

To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in [Hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/). Then, use the [`getEngineTrackingCode()`](#getenginetrackingcode) method.

The `getEngineTrackingCode()` method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.

### Cross-device experimentation

To support visitors who access an app from multiple devices, Kameleoon allows the synchronization of previously collected visitor data across each of the visitor's devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices are available in the [article on cross-device experimentation](/developer-docs/cross-device-experimentation).

#### Synchronizing custom data across devices

Although custom mapping synchronization is used to align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not required:

**Same user ID across devices**
If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the `getRemoteVisitorData()` method when you want to sync the data collected between multiple devices.

**Multi-server instances with consistent IDs**
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with `getRemoteVisitorData()`) is sufficient without additional custom mapping sync.

Customers who need additional data can refer to the [`getRemoteVisitorData()`](#getremotevisitordata) method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the `visitorCode`, which can also be referred to as `userId`) is used consistently between the two devices for accurate data retrieval.

<Note>
  If you want to sync collected data in real time, you need to choose the scope **Visitor** for your custom data.
</Note>

```php title="Device A" theme={null}
// In this example, Custom data with index `90` was set to "Visitor" scope on Kameleoon.
const VISITOR_SCOPE_CUSTOM_DATA_INDEX = 90;

$kameleoonClient->addData($visitorCode, new CustomData(VISITOR_SCOPE_CUSTOM_DATA_INDEX, "your data"));
$kameleoonClient->flush($visitorCode);
```

```php title="Device B" theme={null}
// Call the `getRemoteVisitorData` method before working with the data.
$kameleoonClient->getRemoteVisitorData($visitorCode);

// After the call, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
// So, "your data" will be available to target and track the visitor.
```

#### Using custom data for session merging

[Cross-device experimentation](/developer-docs/cross-device-experimentation) allows for combining a visitor's history across each of their devices (history reconciliation). History reconciliation allows merging different visitor sessions into one. To reconcile visit history, use [`CustomData`](#customdata) to provide a unique identifier for the visitor. For more information, see the [dedicated documentation](/developer-docs/cross-device-experimentation/#activating-cross-device-history-reconciliation).

After cross-device reconciliation is enabled, calling [`getRemoteVisitorData()`](#getremotevisitordata) with the parameter `userId` retrieves all known data for a given user.

Sessions with the same identifier will always be shown the same variation in an experiment. In the Visitor view of your experiment's results pages, these sessions will appear as a single visitor.

The SDK configuration ensures that associated sessions always see the same variation of the experiment. However, there are some limitations regarding cross-device variation allocation. These limitations are outlined [here](/developer-docs/cross-device-experimentation#critical-points-and-practical-insights).

Follow the [activating cross-device history reconciliation](#cross-device-experimentation) guide to set up your custom data on the Kameleoon platform.

Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:

* `getRemoteVisitorData()` with added `UniqueIdentifier(true)` - to retrieve data for all linked visitors.
* [`trackConversion()`](#trackconversion) or [`flush()`](#flush) with added `UniqueIdentifier(true)` data - to track some data for specific visitor that is associated with another visitor.

<Tip>
  As the custom data you use as the identifier must be set to **Visitor scope**, you need to use [cross-device custom data synchronization](/developer-docs/cross-device-experimentation) to retrieve the identifier with the [`getRemoteVisitorData()`](#getremotevisitordata) method on each device.
</Tip>

Here's an example of how to use custom data for session merging.

```php theme={null}
// In this example, `91` represents the Custom Data's index
// configured as a unique identifier in Kameleoon.
const MAPPING_INDEX = 91;
const FEATURE_KEY = "ff123";

// 1. Before the visitor is authenticated

// Retrieve the variation for an unauthenticated visitor.
// Assume `anonymousVisitorCode` is the randomly generated ID for that visitor.
$anonymousVariation = $kameleoonClient->getVariation($anonymousVisitorCode, FEATURE_KEY);

// 2. After the visitor is authenticated

// Assume `userId` is the authenticates visitor's visitor code.
$kameleoonClient->addData($anonymousVisitorCode, new CustomData(MAPPING_INDEX, $userId));
$kameleoonClient->flush($anonymousVisitorCode, null, null, true);

// Indicate that `userId` is a unique identifier.
$kameleoonClient->addData($userId, new UniqueIdentifier(true));

// 3. After the visitor has been authenticated

// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
$userVariation = $kameleoonClient->getVariation($userId, FEATURE_KEY);
$isSameVariation = $userVariation->key == $anonymousVariation->key; // true

// The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
$kameleoonClient->trackConversion($userId, 123, 10.0);

// Additionally, the linked visitors will share all fetched remote visitor data.
$kameleoonClient->getRemoteVisitorData($userId);
```

In this example, the application has a login page. Since the user ID is unknown at the moment of login, an anonymous visitor identifier generated by the [`getVisitorCode()`](#getvisitorcode) method is used. After the user logs in, the anonymous visitor is associated with the user ID and used as a unique identifier for the visitor.

### Using a custom bucketing key

By default, Kameleoon uses a unique, anonymous visitor ID (`visitorCode`) to assign users to feature flag variations. This ID is typically generated and stored on the user's device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). However, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag.

The **Custom Bucketing Key** option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon's assignment logic uses your specified key instead of the default `visitorCode`.

#### Use cases

Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:

* **Account-level or organizational experiments:** For B2B products or scenarios where you want to assign all users from the same organization to the same variation, you can use an identifier like an `accountId`. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.

By implementing a custom bucketing key, you ensure greater consistency and accuracy in your experiments, leading to more reliable results and a better user experience.

#### Technical details

When you configure a custom bucketing key for a feature flag, you provide Kameleoon with a specific identifier from your application's data:

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "newVisitorCode"));
```

* **Providing the custom key:** You provide your custom identifier to the Kameleoon SDK using the [`addData()`](#adddata) method. In this method, you will pass your chosen custom bucketing key as a [`CustomData`](#customdata) object. Here, `newVisitorCode` refers to the identifier you wish to use for your bucketing (for example, the new `userId` or `accountId`).

<Warning>
  For the custom bucketing key to function correctly, it must also be defined and configured for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK's bucketing will not apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this [article](/user-manual/experimentation/feature-experimentation/create-and-manage-flags/create-a-feature-flag#Advanced_Flag_Settings).
</Warning>

* **Bucketing logic:** Once a custom bucketing key is provided through the `addData()` method, all hash calculations for assigning users to variations will use this `newVisitorCode` (your custom key) instead of the default `visitorCode`. Using the `newVisitorCode` means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
* **Data tracking and analytics:** It's crucial to note that while the `newVisitorCode` (your custom key) is used for bucketing decisions, **all subsequent data (tracking events and conversions, for example) is sent and associated with the *original* `visitorCode`.** This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment's broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.

#### Technical requirements

To effectively use a custom bucketing key:

* The key must be a `string`.
* It must be unique for the entity you intend to bucket (for example, if using a `userId`, each user's ID should be unique).
* The key must be available to the SDK at the exact moment the feature flag decision is evaluated for that user or request.

### Targeting conditions

The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions this SDK supports, see [use visit history to target users](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

You can also use your own [external data to target users](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-external-data-to-target-users).

### Logging

The SDK generates logs to reflect various internal processes and issues.

#### Log levels

The SDK supports configuring limiting logging by a log level.

```php theme={null}
use Kameleoon\logging\KameleoonLogger;
use Kameleoon\logging\LogLevel;

// The `NONE` log level does not allow logging.
KameleoonLogger::setLogger(LogLevel::NONE);

// The `ERROR` log level only allows logging issues that may affect the SDK's primary behavior.
KameleoonLogger::setLogger(LogLevel::ERROR);

// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
KameleoonLogger::setLogger(LogLevel::WARNING);

// The `INFO` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
KameleoonLogger::setLogger(LogLevel::INFO);

// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
KameleoonLogger::setLogger(LogLevel::DEBUG);
```

#### Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

<Note>
  Logging limiting by a log level is performed apart from the log handling logic.
</Note>

```php theme={null}
use Kameleoon\logging\KameleoonLogger;
use Kameleoon\logging\Logger;
use Kameleoon\logging\LogLevel;
use Monolog\Logger as MonologLogger;

public class CustomLogger implements Logger {
    // Monolog logger
    private MonologLogger $inner;

    public function __construct(MonologLogger $inner)
    {
        $this->inner = $inner;
    }

    // `log` method accepts logs from the SDK
    public function log($level, string $message): void
    {
        // Custom log handling logic here. For example:
        switch ($level) {
            case LogLevel::ERROR:
                $this->inner->error($message);
                break;
            case LogLevel::WARNING:
                $this->inner->warning($message);
                break;
            case LogLevel::INFO:
                $this->inner->info($message);
                break;
            case LogLevel::DEBUG:
                $this->inner->debug($message);
                break;
        }
    }
}


// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
KameleoonLogger::setLogLevel(LogLevel::DEBUG); // Optional; defaults to `LogLevel::WARNING`.
KameleoonLogger::setLogger(new CustomLogger($inner));
```

## Reference

This is a full reference documentation of the PHP SDK.

### Initialization

#### create()

This method in `Kameleoon\KameleoonClientFactory` creates a `KameleoonClient` instance by providing your SDK configuration in a configuration file. You need to initialize the SDK by creating this instance of `KameleoonClient` before you can use other SDK methods. All interactions with the SDK use this `KameleoonClient` instance. To provide the configuration as a `KameleoonClientConfig` object instead, see the [`createWithConfig`](#createWithConfig) method.

```php theme={null}
require "vendor/autoload.php";

use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;

$siteCode = "a8st4f59bj";

try {
    // Read from default configuration path: "/tmp/kameleoon/php-client/"
    $kameleoonClient = KameleoonClientFactory::create($siteCode);
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}

try {
    $kameleoonClient = KameleoonClientFactory::create($siteCode, "custom/file/path/client-php.json");
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
```

##### Parameters

| Name                  | Type   | Description                                                                                                                                      |
| --------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| siteCode              | String | This is a [unique key](/user-manual/faq#how-do-i-find-my-sitecode) of the Kameleoon project you are using with the SDK. This field is mandatory. |
| configurationFilePath | String | Path to the SDK configuration file. This field is optional and set to `/tmp/kameleoon/client-php.json` by default.                               |

##### Return value

| Type                      | Description                                                                                                  |
| ------------------------- | ------------------------------------------------------------------------------------------------------------ |
| Kameleoon\KameleoonClient | An instance of the **KameleoonClient** class that will be used to manage your experiments and feature flags. |

##### Exceptions thrown

| Type                     | Description                                                                                                                                        |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| SiteCodeIsEmpty          | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| KameleoonException       | Exception that may indicate that the SDK is unable to access the **Kameleoon working directory**.                                                  |

#### createWithConfig()

This method in `Kameleoon\KameleoonClientFactory` creates a `KameleoonClient` instance and allows you to pass your SDK configuration in a `KameleoonClientConfig` object. You need to initialize the SDK by creating this `KameleoonClient` instance before you can use other SDK methods. All interactions with the SDK use this `KameleoonClient` instance. To provide your SDK configuration in a file instead, use the [`create`](#create) method.

```php theme={null}
require "vendor/autoload.php";

use Kameleoon\KameleoonClientConfig;
use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;

$siteCode = "a8st4f59bj";

try {
    $cookieOptions = KameleoonClientConfig::createCookieOptions(
        "example.com", // domain: optional, but strictly recommended
        false, // secure: optional (false by default)
        false, // httponly: optional (false by default)
        "Lax" // samesite: optional (Lax by default)
    );
    $config = new KameleoonClientConfig(
        "<clientId>", // clientId: mandatory
        "<clientSecret>", // clientSecret: mandatory
        "/tmp/kameleoon/php-client/", // kameleoonWorkDir: optional / ("/tmp/kameleoon/php-client/" by default)
        60, // refreshIntervalMinute: in minutes, optional (60 minutes by default)
        10_000, // defaultTimeoutMillisecond: in milliseconds, optional (10_000 ms by default)
        false, // debugMode: optional (false by default)
        $cookieOptions, // cookieOptions: optional
        "development", // environment: optional ("production" by default)
        "example.com", // networkDomain: optional (null by default)
        1024*1024, // requestBodySizeLimitBytes: optional (2560 * 1024 by default)
    );
    $kameleoonClient = KameleoonClientFactory::create($siteCode, $config);
} catch (SiteCodeIsEmpty $ex) {
    // indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
    // indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
    // probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
```

##### Parameters

| Name            | Type                  | Description                                                                                                                         |
| --------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| siteCode        | String                | Code of the website you want to run experiments on. This unique code ID can be found in the Kameleoon app. This field is mandatory. |
| kameleoonConfig | KameleoonClientConfig | Configuration SDK object that you pass. This field is optional.                                                                     |

##### Return value

| Type            | Description                                                                                             |
| --------------- | ------------------------------------------------------------------------------------------------------- |
| KameleoonClient | An instance of the **KameleoonClient** class that you use to manage your experiments and feature flags. |

##### Exceptions thrown

| Type                     | Description                                                                                                                                        |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| SiteCodeIsEmpty          | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| KameleoonException       | Exception that may indicate that the SDK is unable to access the **Kameleoon working directory**.                                                  |

### Feature flags and variations

#### isFeatureActive()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

<Note>
  This method was previously called `activateFeature`, which was removed in SDK version `4.0.0`.
</Note>

This method takes a **visitorCode** and **featureKey** as mandatory arguments to check if the specified feature will be active for a given user.

If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (**true** if the user should have this feature or **false** if not). If a user with a given **visitorCode** is already registered with this feature flag, it will detect the previous **FeatureFlag** value.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

If you specify a `visitorCode`, the `isFeatureActive()` method uses it as the unique visitor identifier, which is useful for [cross-device experimentation](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-external-data-to-target-users). When you specify a `visitorCode` and set the `isUniqueIdentifier` parameter to `true`, the SDK links the flushed data with the visitor associated with the specified identifier.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can also be useful in other edge-case scenarios, such as when you can't access the anonymous `visitorCode` that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
</Note>

<Note>
  Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as `isFeatureActive()`, `getVariation()` or `getVariations()`.

  Use the default `true` value for the `track` parameter when you expose visitors to a variation and need to count them. Set the `track` parameter to `false` only if you call these methods before you expose visitors.

  For example, if you call `getVariations()` to retrieve all variations before you expose visitors, set the `track` parameter to `false`. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.

  Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
</Note>

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "new_checkout";
$hasNewCheckout = false;

try {
    $hasNewCheckout = $kameleoonClient->isFeatureActive($visitorCode, $featureKey, $timeout);
    // disabling tracking
    $hasNewCheckout = $kameleoonClient->isFeatureActive($visitorCode, $featureKey, $timeout, null, false);
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
    $hasNewCheckout = false;
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
    // It appears that the configuration has not been loaded and
    // there is no previously saved version of the configuration available.
} catch (Exception $e) {
    // This is a generic Exception handler which will handle all exceptions.
    echo "Exception: ",  $e->getMessage(), "\n";
}
if ($hasNewCheckout) {
    // Implement new checkout code here.
}
```

<Warning>
  The `isFeatureActive()` method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the **Then, for everyone else serve** default state. If you select **Off** for this default state, the method always returns `false` even when the master feature flag is **On**.
</Warning>

##### Parameters

| Name                            | Type   | Description                                                                                                                                                                                                                                                                            |
| ------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                     | string | Unique identifier of the user. This field is mandatory.                                                                                                                                                                                                                                |
| featureKey                      | string | Key of the feature you want to expose to a user. This field is mandatory.                                                                                                                                                                                                              |
| timeout                         | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |
| isUniqueIdentifier (Deprecated) | ?bool  | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is `null`. The field is optional.                                                                                                                                   |
| track                           | bool   | An optional parameter to enable or disable tracking of the feature evaluation (`true` by default).                                                                                                                                                                                     |

##### Return value

| Type | Description                                                               |
| ---- | ------------------------------------------------------------------------- |
| bool | Value of the feature flag that is registered for a given **visitorCode**. |

##### Exceptions thrown

| Type               | Description                                                                                                                                                                                                                                                                                                  |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| FeatureNotFound    | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                                                                                                                                                                                     |
| DataFileInvalid    | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available.                                                                                                                                                                     |

#### getVariation()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves the [`Variation`](#variation) assigned to a given visitor for a specific feature flag.

This method takes a `visitorCode` and `featureKey` as mandatory arguments. The `track` argument is optional and defaults to `true`.

It returns the assigned `Variation` for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default `Variation` for the given feature flag.

Ensure that proper error handling is implemented in your code to manage potential exceptions.

<Note>
  The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
</Note>

```php theme={null}
$featureKey = "new_checkout";

try {
    $variation = $kameleoonClient->getVariation($visitorCode, $featureKey);
    // disabling tracking
    $variation = $kameleoonClient->getVariation($visitorCode, $featureKey, false);
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // An error has occurred; the feature flag isn't found in the current configuration.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled $e) {
    // The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // The visitor code you passed to the method is invalid and can't be accepted by the SDK.
}

// Fetch a variable value for the assigned variation
$title = $variation->variables["title"]->value;

switch ($variation->key) {
    case "on":
        // Main variation key is selected for visitorCode
        break;
    case "alternative_variation":
        // Alternative variation key
        break;
    default:
        // Default variation key
        break;
}
```

##### Parameters

| Name                                                        | Type     | Description                                                                    | Default |
| ----------------------------------------------------------- | -------- | ------------------------------------------------------------------------------ | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `string` | Unique identifier of the visitor.                                              |         |
| `featureKey` <Badge color="red" size="sm">required</Badge>  | `string` | Key of the feature you want to expose to a visitor.                            |         |
| `track` <Badge color="green" size="sm">optional</Badge>     | `bool`   | An optional parameter to enable or disable tracking of the feature evaluation. | `true`  |

##### Return value

| Type        | Description                                                                           |
| ----------- | ------------------------------------------------------------------------------------- |
| `Variation` | An assigned [`Variation`](#variation) to a given visitor for a specific feature flag. |

##### Exceptions thrown

| Type                         | Description                                                                                                                                                                                                                                                           |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid`         | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                                   |
| `FeatureNotFound`            | Exception indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed in the application). |
| `FeatureEnvironmentDisabled` | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                          |

#### getVariations()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves a map of [`Variation`](#variation) objects assigned to a given visitor across all feature flags.

This method iterates over all available feature flags and returns the assigned `Variation` for each flag associated with the specified visitor. It takes `visitorCode` as a mandatory argument, while `onlyActive` and `track` are optional.

* If `onlyActive` is set to `true`, the method `getVariations()` will return feature flags variations provided the user is not bucketed with the `off` variation.
* The `track` parameter controls whether or not the method will track the variation assignments. By default, it is set to `true`. If set to `false`, the tracking will be disabled.

The returned map consists of feature flag keys as keys and their corresponding `Variation` as values. If no variation is assigned for a feature flag, the method returns the default `Variation` for that flag.

Proper error handling should be implemented to manage potential exceptions.

<Note>
  The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.
</Note>

```php theme={null}
try {
    $variations = $kameleoonClient->getVariations($visitorCode);
    // only active variations
    $variations = $kameleoonClient->getVariations($visitorCode, true);
    // disable tracking
    $variations = $kameleoonClient->getVariations($visitorCode, $onlyActive, false);
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // Handle exception
}
```

##### Parameters

| Name                                                         | Type     | Description                                                                                                       | Default |
| ------------------------------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------- | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge>  | `string` | Unique identifier of the visitor.                                                                                 |         |
| `onlyActive` <Badge color="green" size="sm">optional</Badge> | `bool`   | An optional parameter indicating whether to return variations for active (`true`) or all (`false`) feature flags. | `false` |
| `track` <Badge color="green" size="sm">optional</Badge>      | `bool`   | An optional parameter to enable or disable tracking of the feature evaluation.                                    | `true`  |

##### Return value

| Type                             | Description                                                                                                                         |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `array<string, Types\Variation>` | Map that contains the assigned [`Variation`](#variation) objects of the feature flags using the keys of the corresponding features. |

##### Exceptions thrown

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### setForcedVariation()

The method allows you to programmatically assign a specific [`Variation`](#variation) to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be skipped. It can also be helpful in scenarios like debugging or custom testing.

When a **forced** variation is set, it overrides Kameleoon's real-time evaluation logic. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set `forceTargeting=false` instead.

<Info>
  **Simulated** variations always take precedence in the execution order. If a **simulated** variation calculation is triggered, it will be fully processed and completed first.
</Info>

A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.

The method may throw exceptions under certain conditions (e.g., invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your application remains stable and resilient.

<Warning>
  It’s important to distinguish **forced** variations from **[simulated](#getvisitorcode)** variations:

  * **Forced variations**: Are specific to an individual experiment.
  * **Simulated variations**: Affect the overall **feature flag** result.
</Warning>

```php theme={null}
$experimentId = 9516;
try {
    // Forcing the variation "on" for the experiment 9516 for the visitor
    $kameleoonClient->setForcedVariation($visitorCode, $experimentId, "on");

    // Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
    $kameleoonClient->setForcedVariation($visitorCode, $experimentId, "on", false);

    // Resetting the forced variation for the experiment 9516 for the visitor
    $kameleoonClient->setForcedVariation($visitorCode, $experimentId, null);
} catch (Kameleoon\Exception\KameleoonException $e) {
    // Handling the error
}
```

##### Parameters

| Name                                                             | Type      | Description                                                                                                                                                                                                                                                    | Default |
| ---------------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge>      | `string`  | Unique identifier of the visitor.                                                                                                                                                                                                                              |         |
| `experimentId` <Badge color="red" size="sm">required</Badge>     | `int`     | **Experiment Id** that will be targeted and selected during the evaluation process.                                                                                                                                                                            |         |
| `variationKey` <Badge color="red" size="sm">required</Badge>     | `?string` | **Variation Key** corresponding to a `Variation` that should be forced as the returned value for the experiment. If the value is `null`, the forced variation will be reset.                                                                                   |         |
| `forceTargeting` <Badge color="green" size="sm">optional</Badge> | `bool`    | Indicates whether targeting for the experiment should be forced and skipped (`true`) or applied as in the standard evaluation process (`false`).                                                                                                               | `true`  |
| `timeout` <Badge color="green" size="sm">optional</Badge>        | `?int`    | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. | `null`  |

##### Exceptions thrown

| Type                        | Description                                                                                                                                                                                                                                           |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid`        | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                   |
| `FeatureExperimentNotFound` | Exception indicating that the requested experiment id has not been found in the SDK's internal configuration. This is usually normal and means that the rule's corresponding experiment has not yet been activated on Kameleoon's side.               |
| `FeatureVariationNotFound`  | Exception indicating that the requested variation key(id) has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |

<Info>
  In most cases, only the basic error, `KameleoonException`, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including `Exception`.
</Info>

#### evaluateAudiences()

* 📨 *Sends Tracking Data to Kameleoon*

This method evaluates visitors against all available Audiences Explorer segments and tracks those who match.

`evaluateAudiences()` should be called **after all relevant visitor data has been set or updated**, and **just before** getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria.

After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.

```php theme={null}
try {
    $kameleoonClient->evaluateAudiences($visitorCode);
} catch (Kameleoon\Exception\KameleoonException $e) {
    // Handling the exception
}
```

##### Parameters

| Name                                                        | Type     | Description                                                                                                                                                                                                                                                    | Default |
| ----------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `string` | Unique identifier of the visitor.                                                                                                                                                                                                                              |         |
| `timeout` <Badge color="green" size="sm">optional</Badge>   | `?int`   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. | `null`  |

##### Exceptions thrown

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

<Info>
  In most cases, only the basic error, `KameleoonException`, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including `Exception`.
</Info>

#### getDataFile()

<Tip>
  To evaluate all feature flags, use [`getVariations()`](#getvariations). This method is more efficient than calling `DataFile` and iterating through flags with [`getVariation()`](#getvariation).
</Tip>

Returns the current SDK configuration as a [`DataFile`](#datafile) object.

```php theme={null}
try {
    $dataFile = $kameleoonClient->getDataFile();
} catch (Kameleoon\Exception\KameleoonException $e) {
    // Recommended (but optional) safeguard for unexpected exceptions from third-party libraries
}
```

##### Parameters

| Name                                                    | Type   | Description                                                                                                                                                                                                                                                    |
| ------------------------------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| timeout <Badge color="green" size="sm">optional</Badge> | `?int` | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |

##### Return value

| Type       | Description                                                  |
| ---------- | ------------------------------------------------------------ |
| `DataFile` | The [`DataFile`](#datafile) containing the SDK configuration |

### Visitor data

#### getVisitorCode()

<Note>
  This method was previously called `obtainVisitorCode`, which was removed in SDK version `4.0.0`.
</Note>

Call this method to obtain the Kameleoon **visitorCode** for the current visitor. Calling is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. The implementation logic is described here:

1. First, we check if there is a **kameleoonVisitorCode** cookie or query parameter associated with the current HTTP request. If so, we use this as the visitor identifier.

2. If no cookie or parameter is present in the current request, we have two options for generating an identifier. One option is to create a new identifier randomly, and the other is to use the **defaultVisitorCode** argument if it has been provided. This feature allows our customers to input their own identifiers as visitor codes, which can be beneficial; it seamlessly matches Kameleoon visitors with their own users, eliminating the need for extra look-ups in a matching table.

3. In any case, the server-side (via HTTP header) **kameleoonVisitorCode** cookie is set with the value. The method returns this visitor value.

For more information, refer to [this article](/developer-docs/feature-experimentation/get-started/hybrid-experimentation/).

<Note>
  If you provide your own `visitorCode`, its uniqueness must be guaranteed on your end - the SDK cannot check it. Also note that the length of `visitorCode` is limited to **255** characters. Any excess characters will throw an exception.
</Note>

<Info>
  The `getVisitorCode()` method allows you to set **simulated** variations for a visitor. When cookies (from a **request** or **document**) contain the key `kameleoonSimulationFFData`, the standard evaluation process is bypassed. Instead, the method directly returns a [`Variation`](#variation) based on the provided data.

  You can apply simulations in two ways:

  * **Automatically (recommended):** If using Kameleoon Web Experimentation or the SDK in [Hybrid mode](/developer-docs/feature-experimentation/get-started/hybrid-experimentation#linking-feature-experiments-with-front-end-tracking-code), the cookie is created automatically when simulating a variant's display using the [Simulation Panel](/user-manual/experimentation/feature-experimentation/using-the-rollout-planner/validation-and-rollback/using-simulation-mode).
  * **Manually:** Set the `kameleoonSimulationFFData` cookie manually.

  It’s important to distinguish **simulated** variations from **[forced](#setforcedvariation)** variations:

  * **Simulated variations**: Affect the overall **feature flag** result.
  * **Forced variations**: Are specific to an individual experiment.

  ⚙️ **Manual setup**

  Please ensure the `kameleoonSimulationFFData` cookie follows this format:

  * `kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}`: Simulates the variation with `varId` of experiment `expId` for the given `featureKey`.
  * `kameleoonSimulationFFData={"featureKey":{"expId":0}}`: Simulates the default variation (defined in the **Then, for everyone else in Production, serve** section) for the given `featureKey`.

  ⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as [`encodeURIComponent`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent).
</Info>

```php theme={null}
require "vendor/autoload.php";

// The cookie's domain must be provided in the configuration file if no argument is given.

$visitorCode = $kameleoonClient->getVisitorCode();

// default visitor code provided
$visitorCode = $kameleoonClient->getVisitorCode($defaultVisitorCode);
```

##### Parameters

| Name               | Type   | Description                                                                                                                                                                                                                                                                            |
| ------------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| defaultVisitorCode | String | This parameter will be used as the **visitorCode** if no existing **kameleoonVisitorCode** cookie is found on the request. This field is optional, and, by default, a random **visitorCode** will be generated.                                                                        |
| timeout            | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |

##### Return value

| Type   | Description                                                                                                                 |
| ------ | --------------------------------------------------------------------------------------------------------------------------- |
| String | A **visitorCode** that will be associated with this particular user and should be used with most of the methods of the SDK. |

##### Exceptions thrown

| Type                     | Description                                                                                                                                                      |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| InvalidArgumentException | Exception indicating that the cookie's domain value was not provided (either via the configuration file, or via the **topLevelDomain** parameter on the method). |

#### addData()

The `addData()` method adds [targeting data](#data-types) to storage so other methods can use the data to decide whether or not to target the current visitor.

The `addData()` method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the [`flush()`](#flush) method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered by the `flush()`.

The [`trackConversion()`](#trackconversion) method also sends out any previously associated data, just like the `flush()`. The same holds true for [`getVariation()`](#getvariation) and [`getVariations()`](#getvariations) methods if an experimentation rule is triggered.

<Tip>
  Each visitor can only have one instance of associated data for most data types. However, [`CustomData`](#customdata) is an exception. Visitors can have one instance of associated `CustomData` per index.
</Tip>

```php theme={null}
// Add a single data item (tracked by default)
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME));

// Add multiple data items (tracked by default)
$kameleoonClient->addData(
    $visitorCode,
    new Kameleoon\Data\PageView("https://url.com", "title", [3]),
    new Kameleoon\Data\UserAgent("UserAgent")
);

// Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
$kameleoonClient->addData(
    $visitorCode,
    false,
    new Kameleoon\Data\PageView("https://url.com", "title", [3]),
    new Kameleoon\Data\UserAgent("UserAgent")
);
```

##### Parameters

| Name                                                        | Type      | Description                                                                                                                                                                                  | Default value |
| ----------------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `string`  | Unique identifier of the visitor.                                                                                                                                                            |               |
| `track` <Badge color="green" size="sm">optional</Badge>     | `bool`    | Specifies whether the added data is eligible for tracking. When set to `false`, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | `true`        |
| `data` <Badge color="red" size="sm">required</Badge>        | `...Data` | Collection of Kameleoon data types.                                                                                                                                                          |               |

##### Exceptions

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

#### flush()

* 📨 *Sends Tracking Data to Kameleoon*

The `flush()` method is responsible for sending the Kameleoon data linked to a specific visitor. It triggers a tracking request that includes all the data previously added with the `addData` method, which has not yet been sent during an earlier call to [one of the methods](/developer-docs/feature-experimentation/technical-reference/faq-global#when-does-the-sdk-send-a-tracking-request-for-analytics). `flush()` is non-blocking, as the server call is made asynchronously, unless the `instant` parameter is set to `true`.

The `flush()` function lets you decide when the data linked to a specific `visitorCode` is sent to our servers. For example, if you call `addData()` multiple times—say a dozen times—it would be inefficient to send data to the server every time you perform a call. Instead, you can gather all your data first and then call `flush()` once at the end to send everything at once.

If you specify a `visitorCode`, the `flush()` method uses it as the unique visitor identifier, which is useful for [cross-device experimentation](/developer-docs/cross-device-experimentation). When you specify a `visitorCode` and set the `isUniqueIdentifier` parameter to `true`, the SDK links the flushed data with the visitor associated with the specified identifier.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.
</Note>

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();

$kameleoonClient->addData(
    $visitorCode,
    new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME).
    new Kameleoon\Data\PageView("https://url.com", "title", array(3)),
    new Kameleoon\Data\Conversion(32, 10, false)
);

$kameleoonClient->flush($visitorCode); // Interval tracking, non-blocking operation

$kameleoonClient->flush($visitorCode, null, null, true); // Instant tracking, blocking operation

// if you operate with unique ID
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
$kameleoonClient->flush($visitorCode);
```

##### Parameters

| Name                            | Type   | Description                                                                                                                                                                                                                                                                            |
| ------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                     | string | Unique identifier of the user. This field is mandatory.                                                                                                                                                                                                                                |
| timeout                         | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |
| isUniqueIdentifier (Deprecated) | ?bool  | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is `null`. The field is optional.                                                                                                                                   |
| instant                         | bool   | Boolean flag indicating whether the data should be sent instantly (`true`) or according to the scheduled tracking interval (`false`). If not provided, the default value is `false`. This field is optional.                                                                           |

#### getRemoteData()

<Note>
  This method was previously called `retrieveDataFromRemoteSource`, which was removed in SDK version `4.0.0`.
</Note>

The `getRemoteData()` method lets you retrieve data based on a **key** you provide for a specific **siteCode** (set in `KameleoonClientFactory.create()`). A Kameleoon server stores this data. The Data API is typically used to save this data on our remote servers. This method, combined with our scalable servers, makes storing large amounts of data easy. You can then access this data later for each visitor or user.

```php theme={null}
$test_value = $kameleoonClient->getRemoteData("test"); // default timeout will be used

$test_value = $kameleoonClient->getRemoteData("test", 1000); // 1000 milliseconds timeout

try {
    $test_value = $kameleoonClient->getRemoteData("test");
} catch (Exception $e) {
    // Timeout or Json Decoding Exception
}
```

##### Parameters

| Name    | Type   | Description                                                                                                                                                                                                                                                                            |
| ------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| key     | string | The key that the data you try to get is associated with. This field is mandatory.                                                                                                                                                                                                      |
| timeout | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |

##### Return value

| Type   | Description                                                  |
| ------ | ------------------------------------------------------------ |
| Object | Object associated with retrieving data for specific **key**. |

##### Exceptions thrown

| Type      | Description                                                                                                   |
| --------- | ------------------------------------------------------------------------------------------------------------- |
| Exception | Exception indicating that the request timed out or retrieved data can't be decoded with `json_decode` method. |

#### getRemoteVisitorData()

`getRemoteVisitorData()` is an asynchronous method for retrieving Kameleoon Visits Data for the `visitorCode` from the Kameleoon Data API. The method adds data to storage for other methods to use when making targeting decisions.

Data obtained using this method plays an important role when you want to:

* use data collected from other devices.
* access a user's history, such as previously visited pages during past visits.
* use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.

Read [this article](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation) for a better understanding of possible use cases.

<Warning>
  By default, `getRemoteVisitorData()` automatically retrieves the latest stored custom data with `scope=Visitor` and attaches them to the visitor without the need to call the method `addData()`. It is particularly useful for [synchronizing custom data between multiple devices](/developer-docs/sdks/web-sdks/nodejs-sdk#synchronizing-custom-data-across-devices).
</Warning>

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.
</Note>

```php theme={null}
$visitorCode = "visitorCode";

// Visitor data will be fetched and automatically added for `visitorCode`
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, null); // default timeout will be used
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, 1000); // 1000 milliseconds timeout

// If you only want to fetch data and add it yourself manually, set shouldAddData == `false`
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, null, false); // default timeout will be used
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, 1000, false); // 1000 milliseconds timeout
```

##### Parameters

| Name                            | Type                                      | Description                                                                                                                                                                                                                                                                                                   |
| ------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                     | `string`                                  | The visitor code for which you want to retrieve the assigned data. This field is mandatory.                                                                                                                                                                                                                   |
| timeout                         | `?int`                                    | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration.                        |
| addData                         | `bool`                                    | A boolean indicating whether the method should automatically add retrieved data for a visitor. If not specified, the default value is **true**. This field is optional.                                                                                                                                       |
| filter                          | `Kameleoon\Types\RemoteVisitorDataFilter` | Filter for specifying what data should be retrieved from visits, by default only `CustomData` is retrieved from the current and latest previous visit (`new RemoteVisitorDataFilter(1, true, true)` or `new RemoteVisitorDataFilter()`). Other filters parameters are set to `false`. This field is optional. |
| isUniqueIdentifier (Deprecated) | `?bool`                                   | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is `null`. The field is optional.                                                                                                                                                          |

##### Return value

| Type                    | Description                                   |
| ----------------------- | --------------------------------------------- |
| `array<Kameleoon\Data>` | A list of data assigned to the given visitor. |

##### Using parameters in getRemoteVisitorData()

The `getRemoteVisitorData()` method offers flexibility by allowing you to define various parameters when retrieving data on visitors. Whether you're targeting based on goals, experiments, or variations, the same approach applies across all data types.

For example, let's say you want to retrieve data on visitors who completed a goal "Order transaction". You can specify parameters within the `getRemoteVisitorData()` method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the `previousVisitAmount` parameter to 5 and `conversions` to true.

The flexibility shown in this example is not limited to goal data. You can use parameters within the `getRemoteVisitorData()` method to retrieve data on a variety of visitor behaviors.

<Note>
  Here is the list of available `Kameleoon\Types\RemoteVisitorDataFilter` options:

  | Name                                                                | Type   | Description                                                                                                                                                                                                                                                                                                                                     | Default |
  | ------------------------------------------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
  | previousVisitAmount <Badge color="green" size="sm">optional</Badge> | `int`  | Number of previous visits to retrieve data from. Number between `1` and `25`                                                                                                                                                                                                                                                                    | `1`     |
  | currentVisit <Badge color="green" size="sm">optional</Badge>        | `bool` | If true, current visit data will be retrieved                                                                                                                                                                                                                                                                                                   | `true`  |
  | customData <Badge color="green" size="sm">optional</Badge>          | `bool` | If true, custom data will be retrieved.                                                                                                                                                                                                                                                                                                         | `true`  |
  | pageViews <Badge color="green" size="sm">optional</Badge>           | `bool` | If true, page data will be retrieved.                                                                                                                                                                                                                                                                                                           | `false` |
  | geolocation <Badge color="green" size="sm">optional</Badge>         | `bool` | If true, geolocation data will be retrieved.                                                                                                                                                                                                                                                                                                    | `false` |
  | device <Badge color="green" size="sm">optional</Badge>              | `bool` | If true, device data will be retrieved.                                                                                                                                                                                                                                                                                                         | `false` |
  | browser <Badge color="green" size="sm">optional</Badge>             | `bool` | If true, browser data will be retrieved.                                                                                                                                                                                                                                                                                                        | `false` |
  | operatingSystem <Badge color="green" size="sm">optional</Badge>     | `bool` | If true, operating system data will be retrieved.                                                                                                                                                                                                                                                                                               | `false` |
  | conversions <Badge color="green" size="sm">optional</Badge>         | `bool` | If true, conversion data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | experiments <Badge color="green" size="sm">optional</Badge>         | `bool` | If true, experiment data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | kcs <Badge color="green" size="sm">optional</Badge>                 | `bool` | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the [AI Predictive Targeting add-on](/user-manual/assets/segments/target-users-based-on-likelihood-to-convert)                                                                                                                                                            | `false` |
  | visitorCode <Badge color="green" size="sm">optional</Badge>         | `bool` | If true, Kameleoon will retrieve the `visitorCode` from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their `visitorCode`, always receives the same variation across visits for [Cross-device experimentation](/developer-docs/cross-device-experimentation). | `true`  |
  | cbs <Badge color="green" size="sm">optional</Badge>                 | `bool` | If true, Contextual Bandit score data will be retrieved.                                                                                                                                                                                                                                                                                        | `false` |
  | personalization <Badge color="green" size="sm">optional</Badge>     | `bool` | If true, personalization data will be retrieved. This is required for the personalization condition.                                                                                                                                                                                                                                            | `false` |
</Note>

#### getVisitorWarehouseAudience()

This method retrieves all audience data associated with the visitor in your data warehouse using the specified `visitorCode` and `warehouseKey`. The `warehouseKey` is typically your internal user ID. The `customDataIndex` parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the [warehouse targeting documentation](/user-manual/integrations/data-warehouses/bigquery/use-bigquery-as-a-source-audience-targeting) for additional details. The method passes the result to the returned future as a `CustomData` object, confirming that the data has been added to the visitor and is available for targeting purposes.

```php theme={null}
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience($visitorCode, $customDataIndex);

// If you need to specify warehouse key
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience(
    $visitorCode, $customDataIndex, $warehouseKeyValue
);

// If you need to specify warehouse key & timeout
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience(
    $visitorCode, $customDataIndex, $warehouseKeyValue, 2000
);
```

##### Parameters

| Name            | Type   | Description                                                                                                                                                                                                                                                                            |
| --------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode     | string | The unique identifier of the visitor for whom you want to retrieve and add the data.                                                                                                                                                                                                   |
| customDataIndex | int    | An integer representing the index of the custom data you want to use to target your BigQuery Audiences.                                                                                                                                                                                |
| warehouseKey    | string | The unique key to identify the warehouse data (usually, your internal user ID). This field is optional.                                                                                                                                                                                |
| timeout         | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |

##### Return value

| Type          | Description                                                                                                                                                           |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `?Customdata` | `CustomData` instance confirming that the data has been added to the visitor. If value is `null`, the request is failed and `CustomData` wasn't added to the visitor. |

##### Exceptions thrown

| Type                 | Description                                                                                                          |
| -------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid (it is either empty or longer than 255 characters). |

#### setLegalConsent()

You must use this method to specify whether the visitor has given legal consent to use thier personal data. Setting the `legalConsent` parameter to `false` limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the [consent management policy](/user-manual/project-management/consent-management-policy).

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();
$kameleoonClient->setLegalConsent($visitorCode, true);
```

##### Parameters

| Name         | Type   | Description                                                                                                                                                                                                             |
| ------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode  | string | The user's unique identifier. This field is required.                                                                                                                                                                   |
| legalConsent | bool   | A boolean value representing the legal consent status. `true` indicates the visitor has given legal consent, `false` indicates the visitor has never provided, or has withdrawn, legal consent. This field is required. |

##### Exceptions thrown

| Type               | Description                                                                                              |
| ------------------ | -------------------------------------------------------------------------------------------------------- |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |

##### Consent revocation behavior

When you call `setLegalConsent()` with `legalConsent=false`, the SDK does not delete the `kameleoonVisitorCode` cookie. Instead, it stops extending the cookie's expiration date, allowing the cookie to persist until it naturally expires.

If your compliance requirements demand the immediate removal of the cookie file upon opt-out, you must delete it manually using your framework’s native cookie management methods. The SDK will not remove the file automatically.

### Goals and third party analytics

#### getEngineTrackingCode()

Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the `getEngineTrackingCode()` method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.

Refer to [hybrid experimentation](/developer-docs/feature-experimentation/get-started/hybrid-experimentation) for more information on implementing this method.

```php theme={null}
$engineTrackingCode = $kameleoonClient->getEngineTrackingCode($visitorCode);
```

<Note>
  * To use this feature, implement both the PHP SDK and Kameleoon [Engine.js](/developer-docs/web-experimentation/implementation-and-deployment/standard-implementation). Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing `</body>` tag.
  * If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the [JavaScript / TypeScript SDK](/developer-docs/sdks/web-sdks/js-sdk). This option works well for [serverless edge compute platforms](/developer-docs/feature-experimentation/implementation-and-deployment/serverless-edge-compute-starter-kits). The JavaScript / TypeScript SDK automatically tracks variations when you call [`getVisitorCode`](/developer-docs/sdks/web-sdks/js-sdk#getvisitorcode), as long as you add the corresponding experiment assignments to `window.kameleoonQueue`.
  * You can insert the returned tracking code directly into an HTML `<script>` tag.

  ```html theme={null}
  <html lang="en">
    <body>
      <script>
        const engineTrackingCode = `
          window.kameleoonQueue = window.kameleoonQueue || [];
          window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
          window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
          window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
        `;
        const script = document.createElement('script');

        script.textContent = engineTrackingCode;
        document.body.appendChild(script);
      </script>

    </body>
  </html>
  ```

  In this example, `123456` and `234567` are experiment IDs, and `7890` and `8901` are variation IDs. In your implementation, the SDK generates these values in the returned tracking code.
</Note>

##### Parameters

| Name                                                        | Type     | Description                       |
| ----------------------------------------------------------- | -------- | --------------------------------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `string` | Unique identifier of the visitor. |

##### Return value

| Type     | Description                              |
| -------- | ---------------------------------------- |
| `string` | JavaScript code to insert into the page. |

#### trackConversion()

* 📨 *Sends Tracking Data to Kameleoon*

Use this method to track a conversion for a specific [goal](/user-manual/assets/goals/create-a-goal) and user. This method requires `visitorCode` and `goalId`. In addition, this method also accepts an optional `revenue`, `negative` and `metadata` arguments. The `visitorCode` is usually identical to the one that was used when triggering the experiment.

The `trackConversion()` method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can also be useful in other edge-case scenarios, such as when you can't access the anonymous `visitorCode` that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
</Note>

```php theme={null}
require "vendor/autoload.php";

$kameleoonClient = Kameleoon\KameleoonClientFactory::create("a8st4f59bj", "/tmp/kameleoon/client-php.json");
$visitorCode = $kameleoonClient->getVisitorCode();
$goalID = 83023;

$kameleoonClient->trackConversion($visitorCode, $goalID);

// if you operate with unique ID
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
$kameleoonClient->trackConversion($visitorCode, $goalID, 0.0);

// Add metadata
$cd = new Kameleoon\Data\CustomData(1, "metadata");
$kameleoonClient->trackConversion($visitorCode, $goalID, 0.0, null, null, false, [$cd]);
```

##### Parameters

| Name                                                        | Type                 | Description                                                                                                                                                                                                                                                                                                                          | Default |
| ----------------------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `string`             | Unique identifier of the visitor.                                                                                                                                                                                                                                                                                                    |         |
| `goalId` <Badge color="red" size="sm">required</Badge>      | `int`                | ID of the goal.                                                                                                                                                                                                                                                                                                                      |         |
| `revenue` <Badge color="green" size="sm">optional</Badge>   | `float`              | Revenue of the conversion.                                                                                                                                                                                                                                                                                                           | `0`     |
| `negative` <Badge color="green" size="sm">optional</Badge>  | `bool`               | Defines if the revenue is positive or negative.                                                                                                                                                                                                                                                                                      | `false` |
| `metadata` <Badge color="green" size="sm">optional</Badge>  | `?array<CustomData>` | Lets you set specific values for custom data which have been defined as metadata for the goal in the Kameleoon App. Example: `[CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]`. In this example, `5` and `6` are the indexes of the custom data (5 = “Payment Type”, 6 = “Delivery Method”). | `null`  |
| `isUniqueIdentifier` *(deprecated)*                         | `bool`               | An optional parameter for specifying if the visitorCode is a unique identifier.                                                                                                                                                                                                                                                      | `false` |

<Note>
  metadata values are accessible through [raw data exports](/user-manual/experiment-analytics/analyze-results/results-page-actions#Export) and [the results page](/user-manual/experiment-analytics/analyze-results/goal-metadata).

  If the `metadata` parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the [`addData()`](#adddata) method. If the parameter is omitted, Kameleoon will use the last tracked values for those [`CustomData`](#customdata) prior to the conversion and within the same visit.

  Kameleoon will only consider the metadata values that are explicitly passed as parameters to the `trackConversion()` method.

  In the example below, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value 'Amex Credit Card').

  ```php theme={null}
  $kameleoonClient->addData(
      $visitorCode,
      new CustomData(5, "Credit Card"),
      new CustomData(9, "Express Delivery")
  );
  $kameleoonClient->trackConversion($visitorCode, 10, 0.0, null, null, false, [new CustomData(5, "Amex Credit Card")]);
  ```
</Note>

##### Exceptions

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |

### Data types

You can use the following pre-defined data types from `Kameleoon\Data`.

#### Browser

The `Browser` data set stored here can be used to filter experiment and personalization reports by any value associated with it.

| Name                                                        | Type    | Description                                                                                     |
| ----------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------- |
| `browserType` <Badge color="red" size="sm">required</Badge> | `int`   | List of browsers: `CHROME`, `INTERNET_EXPLORER`, `FIREFOX`, `SAFARI`, `OPERA`, `OTHER`.         |
| `version` <Badge color="green" size="sm">optional</Badge>   | `float` | Version of the browser, floating point number represents major and minor version of the browser |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME));

$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME, 10.0));
```

#### PageView

| Name                                                      | Type          | Description                                        | Default |
| --------------------------------------------------------- | ------------- | -------------------------------------------------- | ------- |
| url <Badge color="red" size="sm">required</Badge>         | `string`      | URL of the page viewed. This field is mandatory.   |         |
| title <Badge color="red" size="sm">required</Badge>       | `?string`     | Title of the page viewed. This field is mandatory. | `null`  |
| referrers <Badge color="green" size="sm">optional</Badge> | `?array<int>` | Referrers of viewed pages. This field is optional. | `null`  |

<Note>
  The index (ID) of the referrer is available in our Back-Office in the Acquisition channel configuration page. Be careful: this index starts at 0, so the first [acquisition channel](/user-manual/assets/advanced-targeting-tools/create-an-acquisition-channel) you create for a given site would have the ID 0, not 1.
</Note>

```php theme={null}
$kameleoonClient->addData(
    $visitorCode,
    new Kameleoon\Data\PageView("https://url.com", "title", [3])
);
```

#### Conversion

The `Conversion` data set stored here can be used to filter experiment and personalization reports by any goal associated with it.

<Tip>
  * Each visitor can have multiple `Conversion` objects.
  * You can find the `goalId` in the Kameleoon app.
</Tip>

| Name                                                       | Type                 | Description                                     | Default |
| ---------------------------------------------------------- | -------------------- | ----------------------------------------------- | ------- |
| `goalId` <Badge color="red" size="sm">required</Badge>     | `int`                | ID of the goal.                                 |         |
| `revenue` <Badge color="green" size="sm">optional</Badge>  | `float`              | Revenue of the conversion                       | `0`     |
| `negative` <Badge color="green" size="sm">optional</Badge> | `bool`               | Defines if the revenue is positive or negative. | `false` |
| `metadata` <Badge color="green" size="sm">optional</Badge> | `?array<CustomData>` | Metadata of the conversion.                     | `null`  |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Conversion(32, 10, false));

$cd = new Kameleoon\Data\CustomData(1, "metadata");
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Conversion(32, 0.0, false, [$cd]));
```

#### CustomData

`CustomData` allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in [segments](/user-manual/assets/segments/create-a-segment/) or as a filter/breakdown in experiment reports.
To learn more about custom data, please refer to this [article](/developer-docs/custom-data).

| Name                                                      | Type           | Description                                                                                                                                                                             | Default |
| --------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| indexOrName <Badge color="red" size="sm">required</Badge> | `int`/`string` | Index or Name of the custom data. **Either `index` or `name` must be provided** to identify the data.                                                                                   |         |
| values <Badge color="red" size="sm">required</Badge>      | `string...`    | Value(s) of the custom data to be stored.                                                                                                                                               |         |
| overwrite <Badge color="green" size="sm">optional</Badge> | `bool`         | Flag to explicitly control how the values are stored and how they appear in reports. [See more](/developer-docs/custom-data#default-logic-when-overwrite-parameter-is-false-or-omitted) | `true`  |

<Note>
  * Each visitor is allowed only one `CustomData` for each unique `index`. Adding another `CustomData` with the same `index` will replace the existing one.

  * The custom data ‘index’ can be found in the [Custom Data dashboard](/user-manual/assets/custom-data/manage-custom-data) under the “INDEX” column.

  * To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: **Use this data only locally for targeting purposes** when creating custom data.

  * Adding a `CustomData` instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
</Note>

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "value"));

// With several values
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "value1", "value2"));

// To set the 'overwrite' flag to false
$kameleoonClient->addData($visitorCode, Kameleoon\Data\CustomData::newWithOverwrite(1, false, "value"));

// To use a name instead of the index
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData("my-custom-data", "value"));

// To use a name instead of the index
// and set the 'overwrite' flag to false
$kameleoonClient->addData($visitorCode, Kameleoon\Data\CustomData::newWithOverwrite("my-custom-data", false, "value"));
```

#### Device

| Name | Type | Description                                                       |
| ---- | ---- | ----------------------------------------------------------------- |
| type | int  | List of devices: PHONE, TABLET, DESKTOP. This field is mandatory. |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Device(Kameleoon\Data\Device::PHONE));
```

#### UserAgent

Keep track of visitors' user-agent information. Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to tackle this issue and recognize known bots and spiders. Kameleoon also uses the `UserAgent` field to filter out bots and other unwanted traffic that might distort your conversion metrics. For more details, see our help article on [bot filtering](/user-manual/faq#how-does-kameleoon-filter-bot-traffic-from-my-results).

If you use internal bots, we suggest that you pass the value **curl/8.0** of the userAgent to exclude them from our analytics.

| Name  | Type   | Description                                                                             |
| ----- | ------ | --------------------------------------------------------------------------------------- |
| value | string | The User-Agent value that will be sent with tracking requests. This field is mandatory. |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UserAgent("TestUserAgent"));
```

#### UniqueIdentifier

If you don't add `UniqueIdentifier` for a visitor, `visitorCode` is used as the unique visitor identifier, which is useful for [Cross-device experimentation](/developer-docs/cross-device-experimentation). When you add `UniqueIdentifier` for a visitor, the SDK links the flushed data with the visitor associated with the specified identifier.

The `isUniqueIdentifier` can be helpful in unique situations; for example, if you cannot access the anonymous `visitorCode` given to a visitor, but you can use an internal ID linked to that visitor through session merging.

| Name  | Type | Description                                                                                   |
| ----- | ---- | --------------------------------------------------------------------------------------------- |
| value | bool | Parameter for specifying if the `visitorCode` is a unique identifier. This field is required. |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
```

#### OperatingSystem

`OperatingSystem` contains information about the operating system on the visitor's device.

| Name | Type  | Description                                                                                                         |
| ---- | ----- | ------------------------------------------------------------------------------------------------------------------- |
| type | `int` | List of operating systems: `WINDOWS`, `MAC`, `IOS`, `LINUX`, `ANDROID` and `WINDOWS_PHONE`. This field is required. |

<Tip>
  Each visitor can only have one `OperatingSystem`. Adding a second `OperatingSystem` overwrites the first one.
</Tip>

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\OperatingSystem(Kameleoon\Data\OperatingSystem::WINDOWS));
```

#### Cookie

`Cookie` contains information about the cookie stored on the visitor's device.

| Name    | Type    | Description                                                                       |
| ------- | ------- | --------------------------------------------------------------------------------- |
| cookies | `array` | A string object map consisting of cookie keys and values. This field is required. |

<Tip>
  Each visitor can only have one `Cookie`. Adding a second `Cookie` overwrites the first one.
</Tip>

```php theme={null}
$cookie = new Kameleoon\Data\Cookie([
   "k1" => "v1",
   "k2" => "v2",
]);
$kameleoonClient->addData($visitorCode, $cookie);
```

#### Geolocation

`Geolocation` contains the visitor's geolocation details.

| Name                                                         | Type                   | Description                                                                                                      |
| ------------------------------------------------------------ | ---------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `country` <Badge color="red" size="sm">required</Badge>      | `string`               | The country of the visitor.                                                                                      |
| `region` <Badge color="green" size="sm">optional</Badge>     | <nobr>`?string`</nobr> | The region of the visitor.                                                                                       |
| `city` <Badge color="green" size="sm">optional</Badge>       | <nobr>`?string`</nobr> | The city of the visitor.                                                                                         |
| `postalCode` <Badge color="green" size="sm">optional</Badge> | <nobr>`?string`</nobr> | The postal code of the visitor.                                                                                  |
| `latitude` <Badge color="green" size="sm">optional</Badge>   | `float`                | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.  |
| `longitude` <Badge color="green" size="sm">optional</Badge>  | `float`                | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |

<Tip>
  * Each visitor can have only one `Geolocation`. Adding a second `Geolocation` overwrites the first one.
</Tip>

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Geolocation("France", "Île-de-France", "Paris"));
```

#### ApplicationVersion

`ApplicationVersion` represents the semantic version number of your application.

<Tip>
  A **visitor** can have only one `ApplicationVersion`. Adding a second instance will overwrite the first one.
</Tip>

| Name                                                    | Type     | Description                                                                                                                                      |
| ------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| version <Badge color="green" size="sm">optional</Badge> | `string` | The mobile application version. This field must follow semantic versioning. Accepted formats are `major`, `major.minor`, or `major.minor.patch`. |

```php theme={null}
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10")); // major

$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10.20")); // major.minor

$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10.20.30")); // major.minor.patch
```

### Returned Types

#### DataFile

The `DataFile` contains the SDK configuration details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name           | Type                         | Description                                                                       |
| -------------- | ---------------------------- | --------------------------------------------------------------------------------- |
| `featureFlags` | `array<string, FeatureFlag>` | A map of [`FeatureFlag`](#featureflag) objects, keyed by feature flag keys.       |
| `dateModified` | `int`                        | The timestamp (in milliseconds) indicating when the `DataFile` was last modified. |

```php theme={null}
// Retrieves the array of feature flags from the DataFile.
// The array is keyed by feature flag identifiers, with each value being a FeatureFlag object.
$featureFlags = $dataFile->featureFlags;

// Retrieves the last modification timestamp of the DataFile.
// The value is an int representing milliseconds since the Unix epoch.
$dateModified = $dataFile->getDateModified();
```

#### FeatureFlag

The `FeatureFlag` represents a set of properties that define a feature flag itself — for example, its [`Variations`](#variation), [`Rules`](#rule), environment status, and other related details.

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name                   | Type                       | Description                                                                |
| ---------------------- | -------------------------- | -------------------------------------------------------------------------- |
| `isEnvironmentEnabled` | `bool`                     | Indicating whether the feature flag is enabled in the current environment. |
| `defaultVariationKey`  | `string`                   | The key of the default variation associated with the feature flag.         |
| `variations`           | `array<string, Variation>` | A map of `Variation` objects, keyed by variation keys.                     |
| `rules`                | `array<Rule>`              | A list of `Rule` objects                                                   |

```php theme={null}
// Check whether the feature flag is enabled in the current environment
$isEnvironmentEnabled = $featureFlag->isEnvironmentEnabled;

// Retrieve the key of the default variation
$defaultVariationKey = $featureFlag->defaultVariationKey;

// Retrieve the default variation object
$defaultVariation = $featureFlag->getDefaultVariation();

// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
$variations = $featureFlag->variations;

// Retrieve all targeting rules associated with the feature flag
$rules = $featureFlag->rules;
```

#### Rule

The `Rule` represents a set of properties that define a rule itself — for example, its [`Variations`](#variation).

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name         | Type                       | Description                                            |
| ------------ | -------------------------- | ------------------------------------------------------ |
| `variations` | `array<string, Variation>` | A map of `Variation` objects, keyed by variation keys. |

```php theme={null}
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
$variations = $rule->variations;
```

#### Variation

`Variation` contains information about the assigned variation to the visitor (or the default variation if no specific assignment exists).

| Name         | Type                      | Description                                                                                                                                             |
| ------------ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name         | `string`                  | The name of the variation.                                                                                                                              |
| key          | `string`                  | The unique key identifying the variation.                                                                                                               |
| id           | `?int`                    | The ID of the assigned variation (or `null` if it's the default variation).                                                                             |
| experimentId | `?int`                    | The ID of the experiment associated with the variation (or `null` if default).                                                                          |
| variables    | `array<string, Variable>` | An array containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated. |

<Note>
  * The `Variation` object provides details about the assigned variation and its associated experiment, while the [`Variable`](#variable) object contains specific details about each variable within a variation.
  * Ensure that your code handles the case where `id` or `experimentId` may be `null`, indicating a default variation.
  * The `variables` array might be empty if no variables are associated with the variation.
</Note>

```php theme={null}
// Retrieving the variation name
$variationName = $variation->name;

// Retrieving the variation key
$variationKey = $variation->key;

// Retrieving the variation id
$variationId = $variation->id;

// Retrieving the experiment id
$experimentId = $variation->experimentId;

// Retrieving the variables map
$variables = $variation->variables;
```

#### Variable

`Variable` contains information about a variable associated with the assigned variation.

| Name  | Type     | Description                                                                                                                                  |
| ----- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| key   | `string` | The unique key identifying the variable.                                                                                                     |
| type  | `string` | The type of the variable. Possible values: **BOOLEAN**, **NUMBER**, **STRING**, **JSON**, **JS**, **CSS**                                    |
| value | `?mixed` | The value of the variable, which can be of the following types: **bool**, **int**, **float**, **string**, **stdClass**, **array**, **null**. |

```php theme={null}
// Retrieving the variables map
$variables = $variation->variables;

// Variable type can be retrieved for further processing
$type = $variables["isDiscount"]->type;

// Retrieving the variable value by key
$isDiscount = (bool) $variables["isDiscount"]->value;

// Variable value can be of different types
$title = (string) $variables["title"]->value;
```

### Deprecated methods

<Warning>
  These methods are deprecated and will be removed in SDK version `5.0.0`.
</Warning>

#### getFeatureVariationKey()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  Use [`getVariation()`](#getvariation) instead.
</Note>

To get feature variation key, call the `getFeatureVariationKey()` method of our SDK.

This method takes a **visitorCode** and **featureKey** as mandatory arguments to get the variation key for a given user.

If a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given **visitorCode** is already registered with this feature flag, it will detect the previous **variation key** value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer's account.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

If you specify a `visitorCode`, the `getFeatureVariationKey()` method uses it as the unique visitor identifier, which is useful for [Cross-device experimentation](/developer-docs/cross-device-experimentation). When you specify a `visitorCode` and set the `isUniqueIdentifier` parameter to `true`, the SDK links the flushed data with the visitor associated with the specified identifier.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` can also be useful in other edge-case scenarios, such as when you can't access the anonymous `visitorCode` that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
</Note>

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "featureKey";
$variationKey = "";

try {
    $variationKey = $kameleoonClient->getFeatureVariationKey($visitorCode, $featureKey);
    switch ($variationKey) {
        case "on":
            // Main variation key is selected for visitorCode
            break;
        case "alternativeVariation":
            // Alternative variation key
            break;
        default:
            // Default variation key
            break;
    }
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
    // It appears that the configuration has not been loaded
    // and there is no previously saved version of the configuration available.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
    // The feature flag is disabled for the environment.
} catch (Exception $e) {
    // This is a generic Exception handler which will handle all exceptions.
    echo "Exception: ",  $e->getMessage(), "\n";
}
```

##### Parameters

| Name                            | Type   | Description                                                                                                                                                                                                                                                                            |
| ------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                     | string | Unique identifier of the user. This field is mandatory.                                                                                                                                                                                                                                |
| featureKey                      | string | Key of the feature you want to expose to a user. This field is mandatory.                                                                                                                                                                                                              |
| timeout                         | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |
| isUniqueIdentifier (Deprecated) | ?bool  | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is `null`. The field is optional.                                                                                                                                   |

##### Return value

| Type   | Description                                                                       |
| ------ | --------------------------------------------------------------------------------- |
| string | Variation key of the feature flag that is registered for a given **visitorCode**. |

##### Exceptions thrown

| Type                       | Description                                                                                                                                                                                                                                                                                                  |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
| FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                                                                 |
| VisitorCodeInvalid         | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                                                                                                                                                                                     |
| DataFileInvalid            | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available.                                                                                                                                                                     |

#### getActiveFeatureListForVisitor()

<Note>
  Use [`getActiveFeatures()`](#getActiveFeatures) instead.
</Note>

This method takes only input parameters: **visitorCode**. Result contains only active feature flags for a given visitor.

```php theme={null}
$visitorCode = "visitor";
$arrayFeatureFlagKeys = $kameleoonClient->getActiveFeatureListForVisitor($visitorCode);
```

##### Arguments

| Name        | Type   | Description                                                                                                                                                                                                                                                                            |
| ----------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode | string | Unique identifier of the user. This field is mandatory.                                                                                                                                                                                                                                |
| timeout     | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |

##### Return value

| Type | Description                                                            |
| ---- | ---------------------------------------------------------------------- |
| any  | List of feature flag keys which are active for a given **visitorCode** |

##### Exceptions thrown

| Type               | Description                                                                                                                              |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                 |
| DataFileInvalid    | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |

#### getActiveFeatures()

<Note>
  Use [`getVariations()`](#getvariations) instead.
</Note>

`getActiveFeatures` method retrieves information about the active feature flags that are available for the specified visitor code.

```php theme={null}
$visitorCode = "visitor";
$arrayActiveFeatures = $kameleoonClient->getActiveFeatures($visitorCode);
```

##### Arguments

| Name        | Type   | Description                                                                                                                                                                                                                                                                            |
| ----------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode | string | Unique identifier of the user. This field is mandatory.                                                                                                                                                                                                                                |
| timeout     | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |

##### Return value

| Type  | Description                                                                                                 |
| ----- | ----------------------------------------------------------------------------------------------------------- |
| array | An array that contains the assigned variations of the active features using the active feature IDs as keys. |

##### Exceptions thrown

| Type               | Description                                                                                                                              |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                 |
| DataFileInvalid    | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |

#### getFeatureVariable()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  - Use [`getVariation()`](#getvariation) instead.
  - This method was previously called `obtainFeatureVariable`, which has been deprecated since SDK version `3.0.0` and will be removed in a future release.
</Note>

To get the variable of a variation key associated with a user, call the `getFeatureVariable()` method.

This method takes a **visitorCode**, **featureKey**, and **variableName** as mandatory arguments to get a variable of the variation key for a given user.

If the user has never been associated with this feature flag, the SDK returns a variable value of the variation key randomly (according to the feature flag rules). If a user with a given **visitorCode** is already registered with this feature flag, the method will detect the **variable** value for the associated **variation**. If the user does not match any of the rules, the default variable will be returned.

Ensure proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

If you specify a `visitorCode`, the `getFeatureVariable()` method uses it as the unique visitor identifier, which is useful for [Cross-device experimentation](/developer-docs/cross-device-experimentation). When you specify a `visitorCode` and set the `isUniqueIdentifier` parameter to `true`, the SDK links the flushed data with the visitor associated with the specified identifier.

<Note>
  The parameter `isUniqueIdentifier` is deprecated. Please use [`UniqueIdentifier`](#uniqueidentifier) instead.

  The `isUniqueIdentifier` is useful in other edge-case scenarios, such as when you can't access the anonymous `visitorCode` that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
</Note>

```php theme={null}
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "featureKey";
$variableName = "variableName";

try {
    $variationValue = $kameleoonClient->getFeatureVariable($visitorCode, $featureKey, $variableName);
    // Your custom code depending on variableValue
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
    // The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
    // VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\FeatureVariableNotFound $e) {
    // Requested variable not defined on Kameleoon's side.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
    // It appears that the configuration has not been loaded
    // and there is no previously saved version of the configuration available.
} catch (Exception $e) {
    // This is a generic Exception handler which will handle all exceptions.
    echo "Exception: " . $e->getMessage() . "\n";
}
```

##### Parameters

| Name                            | Type   | Description                                                                                                                                                                                                                                                                            |
| ------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorCode                     | string | Unique identifier of the user. This field is mandatory.                                                                                                                                                                                                                                |
| featureKey                      | string | Key of the feature you want to expose to a user. This field is mandatory.                                                                                                                                                                                                              |
| variableName                    | string | Name of the variable you want to get a value. This field is mandatory.                                                                                                                                                                                                                 |
| timeout                         | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |
| isUniqueIdentifier (Deprecated) | ?bool  | An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is `null`. The field is optional.                                                                                                                                   |

##### Return value

| Type | Description                                                                                                                                                  |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Any  | Value of variable of variation that is registered for a given **visitorCode** for this feature flag. Possible types: bool, int, float, string, object, array |

##### Exceptions thrown

| Type                       | Description                                                                                                                                                                                                                                                                                                  |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
| FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                                                                 |
| VisitorCodeInvalid         | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters).                                                                                                                                                                                                     |
| FeatureVariableNotFound    | Exception indicating that the requested variable has not been found. Check that the variable's ID (or key) matches your code.                                                                                                                                                                                |
| DataFileInvalid            | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available.                                                                                                                                                                     |

#### getFeatureVariationVariables()

<Note>
  * Use [`getVariation()`](#getvariation) instead.
  * This method was previously called `getFeatureAllVariables`, which was removed in SDK version `4.0.0`.
</Note>

To retrieve the all feature variables, call the `getFeatureVariationVariables()` method. A feature variable can be changed easily via our web application.

This method takes **featureKey** and **variationKey** as mandatory arguments. It will return the data with the object type, as defined on the web interface. The method throws an error (`FeatureNotFound`) if the requested feature flag has not been found in the SDK's client configuration. If the variation key isn't found, the method throws the `FeatureVariationNotFound` error.

```php theme={null}
$featureKey = "test_feature_variables";
$variationKey = "on";

try {
    $variables = $kameleoonClient->getFeatureVariationVariables($featureKey, $variationKey);
    $firstName = $variables["firstName"];
} catch (Kameleoon\Exception\FeatureNotFound $e) {
    // The feature is not yet activated on Kameleoon's side.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
    // The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\FeatureVariationNotFound $e) {
    // The variation is not yet activated on Kameleoon's side, i.e., the associated experiment is not online.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
    // It appears that the configuration has not been loaded
    // and there is no previously saved version of the configuration available.
} catch (Exception $e) {
    // This is a generic Exception handler which will handle all exceptions.
    echo "Exception: " . $e->getMessage() . "\n";
}
```

##### Parameters

| Name         | Type   | Description                                                                                                                                                                                                                                                                            |
| ------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| featureKey   | string | Key of the feature flag you want to obtain. This field is mandatory.                                                                                                                                                                                                                   |
| variationKey | string | Key of the variation you want to obtain. This field is mandatory.                                                                                                                                                                                                                      |
| timeout      | ?int   | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |

##### Return value

| Type | Description                                                                                                                                                   |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Any  | Value of the variation variable that is registered for a given **visitorCode** for this feature flag. Possible types: bool, int, float, string, object, array |

##### Exceptions thrown

| Type                       | Description                                                                                                                                                                                                                                                                                             |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| FeatureNotFound            | Exception indicating that the requested feature ID has not been found in the SDK's internal configuration. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
| FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                                                            |
| FeatureVariationNotFound   | Exception indicating that the requested variation ID has not been found in the SDK's internal configuration. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side.                                                             |
| DataFileInvalid            | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available.                                                                                                                                                                |

#### getFeatureList()

Returns a list of feature flag keys currently available for the SDK.

```php theme={null}
$arrayFeatureKeys = $kameleoonClient->getFeatureList();
```

##### Parameters

| Name                                                    | Type   | Description                                                                                                                                                                                                                                                    |
| ------------------------------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| timeout <Badge color="green" size="sm">optional</Badge> | `?int` | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the [`default_timeout`](#additional-configuration) specified in your configuration. |

##### Return value

| Type            | Description               |
| --------------- | ------------------------- |
| `array<string>` | List of feature flag keys |
