PHP SDK
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.
Changelog: Latest version of the PHP SDK: 4.20.0 Changelog.
SDK methods: For the full reference documentation of the PHP SDK, see the 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)
Please carefully read the sections on installing the cron job and using the PHP SDK without a cron job.
The installation package is available on Packagist. You can install the PHP SDK by adding it as a dependency using Composer:
{
"require": {
"kameleoon/kameleoon-client-php": "^4.18.0"
}
}
Finally, execute the following command to regenerate the autoloader:
composer install
With a cron job (Recommended)
Setting up the cron allows the tracking of data added by the PHP sdk with the addData() method. However, if you are unable to install it, front end tracking can still be implemented following this guide.
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 to benefit from the Kameleoon Application Engine's, engine.js (previously named, kameleoon.js) tracking capabilities. Our SDK provides the getEngineTrackingCode() method, which sends exposure events to Kameleoon or any other analytics solution you use on your website.
With this approach you won't be able to track data added with the 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.
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 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 (required) | Required for authentication to the Kameleoon service. To find your client_id, see the API credentials documentation. | |
clientSecret / client_secret (required) | Required for authentication to the Kameleoon service. To find your client_secret, see the API credentials documentation. | |
kameleoonWorkDir / kameleoon_work_dir (optional) | 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 (optional) | 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 (optional) | 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 (optional) | Controls the Secure cookie attribute. | false |
cookieOptions->httpOnly / cookie_options.http_only (optional) | Controls the HttpOnly cookie attribute. | false |
cookieOptions->sameSite / cookie_options.samesite (optional) | Controls the SameSite cookie attribute. | Lax |
environment / environment (optional) | Environment from which the feature flag’s configuration is to be used. The value can be production, staging, development. See the managing environments article for details. More information | production |
networkDomain / network_domain (optional) | 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 |
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 instead. | false |
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).
To learn more about client_id and client_secret, and how to obtain them, refer to the API credentials article. Note that the Kameleoon PHP SDK uses the Automation API and follows the OAuth 2.0 client credentials flow.
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:
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)
);
$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. 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.
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.
Activating a feature flag
Assigning a unique ID to a user
To assign a unique ID to a user, you can use the 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, 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() or 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 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
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() 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() 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.
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.
If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's Custom Data feature. Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the flush() method to send the collected data to Kameleoon servers for analysis.
To ensure your results are accurate, it's recommended to filter out bots by using the UserAgent data type.
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() 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() 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. Then, use the 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.
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() 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.
If you want to sync collected data in real time, you need to choose the scope Visitor for your custom data.
// 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);
// 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 allows for combining a visitor's history across each of their devices (history reconciliation). History reconciliation allow merging different visitor sessions into one. To reconcile visit history, use CustomData to provide a unique identifier for the visitor. For more information, see the dedicated documentation.
After cross-device reconciliation is enabled, calling 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.
Follow the activating cross-device history reconciliation 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 addedUniqueIdentifier(true)- to retrieve data for all linked visitors.trackConversion()orflush()with addedUniqueIdentifier(true)data - to track some data for specific visitor that is associated with another visitor.
As the custom data you use as the identifier must be set to Visitor scope, you need to use cross-device custom data synchronization to retrieve the identifier with the getRemoteVisitorData() method on each device.
Here's an example of how to use custom data for session merging.
// 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() 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:
$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()method. In this method, you will pass your chosen custom bucketing key as aCustomDataobject. Here,newVisitorCoderefers to the identifier you wish to use for your bucketing (for example, the newuserIdoraccountId).
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.
- Bucketing logic: Once a custom bucketing key is provided through the
addData()method, all hash calculations for assigning users to variations will use thisnewVisitorCode(your custom key) instead of the defaultvisitorCode. Using thenewVisitorCodemeans 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 originalvisitorCode. 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 requirementes
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.
You can also use your own 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.
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.
Logging limiting by a log level is performed apart from the log handling logic.
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 method.
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**
}
Arguments
| Name | Type | Description |
|---|---|---|
| siteCode | String | This is a unique key 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 method.
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)
);
$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**
}
Arguments
| 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
trackparameter)
This method was previously called activateFeature, which was removed in SDK version 4.0.0.
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. 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.
The parameter isUniqueIdentifier is deprecated. Please use 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.
$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.
}
Arguments
| 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 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 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
trackparameter)
Retrieves the 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.
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.
$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;
}
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (required) | string | Unique identifier of the user. | |
| featureKey (required) | string | Key of the feature you want to expose to a user. | |
| track (optional) | bool | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
| Type | Description |
|---|---|
Variation | An assigned 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
trackparameter)
Retrieves a map of 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
onlyActiveis set totrue, the methodgetVariations()will return feature flags variations provided the user is not bucketed with theoffvariation. - The
trackparameter controls whether or not the method will track the variation assignments. By default, it is set totrue. If set tofalse, 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.
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.
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
}
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (required) | string | Unique identifier of the user. | |
| onlyActive (optional) | bool | An optional parameter indicating whether to return variations for active (true) or all (false) feature flags. | false |
| track (optional) | 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 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. |
getFeatureList()
Returns a list of feature flag keys currently available for the SDK.
$arrayFeatureKeys = $kameleoonClient->getFeatureList();
Arguments
| Name | Type | Description |
|---|---|---|
| timeout (optional) | ?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 specified in your configuration. |
Return value
| Type | Description |
|---|---|
array<string> | List of feature flag keys |
setForcedVariation()
The method allows you to programmatically assign a specific 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.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
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.
It’s important to distinguish forced variations from simulated variations:
- Forced variations: Are specific to an individual experiment.
- Simulated variations: Affect the overall feature flag result.
$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
}
Arguments
| Name | Type | Description | Default |
|---|---|---|---|
| visitorCode (required) | string | Unique identifier of the user. | |
| experimentId (required) | int | Experiment Id that will be targeted and selected during the evaluation process. | |
| variationKey (required) | ?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 (optional) | bool | Indicates whether targeting for the experiment should be forced and skipped (true) or applied as in the standard evaluation process (false). | true |
| timeout (optional) | ?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 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. |
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.
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.
try {
$kameleoonClient->evaluateAudiences($visitorCode);
} catch (Kameleoon\Exception\KameleoonException $e) {
// Handling the exception
}