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.5.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)
The kameleoon/ directory corresponds to the PHP package itself, which should be used with the Composer dependency manager.
Install this directory in your composer hierarchy (so you should have vendor/kameleoon/client/src
). Then edit composer.json
and add a Kameleoon entry:
"autoload": {
"psr-4": {
"Kameleoon\\": "vendor/kameleoon-php-client/kameleoon/client/src"
}
}
Finally, execute the following command to regenerate the autoloader:
composer dump-autoload -o
Installing the cron job
The job/ directory corresponds to a job that must be executed via a standard job scheduler (like cron). We suggest to install the script itself to /usr/local/opt/kameleoon/kameleoon-client-php-process-queries.sh
and to use our default supplied crontab entry. But you can install it in another location and modify the crontab entry accordingly.
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
. With the current version of the PHP SDK, 6 keys are available:
- client_id: a
client_id
is required for authentication to the Kameleoon service. - client_secret: a
client_secret
is required for authentication to the Kameleoon service. - kameleoon_work_dir: this specifies a working directory for the PHP client (who will create files on this directory). It needs to be writable by the PHP user. If not specified, by default the directory will be
/tmp/kameleoon/client-php/
. - refresh_interval_minute: this specifies the refresh interval, in minutes, of the configuration for experiments and personalizations (the active experiments and personalizations are fetched from the Kameleoon servers). It means that once you launch an experiment, pause it, or stop it the changes can take (at most) the duration of this interval to be propagated in production to your servers. If not specified, the default interval is 60 minutes.
- default_timeout_millisecond: the parameter sets the time limit for network requests made by the SDK, measured in milliseconds. If this parameter is not defined, the default timeout value is 10_000 milliseconds.
- cookie_options: this is a map containing configuration options for the kameleoonVisitorCode cookie set by the
getVisitorCode()
method. Following keys are available:- domain: the current top-level domain for your website . Use the format:
example.com
. Don't includehttps://
,www
, or other subdomains. Kameleoon uses this information to set the corresponding cookie on the top-level domain. This field is mandatory. - secure: this controls the secure cookie attribute. Default value is false.
- http_only: this controls the httponly cookie attribute. Default value is false.
- samesite: this controls the samesite cookie attribute. Default value is None.
- domain: the current top-level domain for your website . Use the format:
- debug_mode: this parameter sends additional information to our tracking servers to help analyze difficult issues. It should usually be off (false), but activating it (true) has no impact on the SDK performance.
- environment: an option specifying which feature flag configuration will be used, by default each feature flag is split into production, staging, development. If not specified, will be set to default value of production. More information
If you use another path for the configuration file than the default one (/tmp/kameleoon/client-php.json
), you will need to:
-pass the path of your configuration file 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 called as
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
, as well as 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;
use Kameleoon\Exception\SiteCodeIsEmpty;
use Kameleoon\Exception\ConfigCredentialsInvalid;
$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
}
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
}
try {
$cookieOptions = KameleoonClientConfig::createCookies(
"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)
);
$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
}
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 will 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. This is easy to do, because this 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 (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 that have been collected on other devices or to access past data points about a user (which would have been collected client-side if you are using Kameleoon in Hybrid mode), use the GetRemoteVisitorData()
method. This method asynchronously fetches data from our servers. However, it is important you 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 of a feature flag.
To learn more about available targeting conditions, read our 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.
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 supported by this SDK, 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 allows no logging.
KameleoonLogger::setLogger(LogLevel::NONE);
// The `ERROR` log level allows to log only issues that may affect the SDK's main behaviour.
KameleoonLogger::setLogger(LogLevel::ERROR);
// The `WARNING` log level allows to log issues which may require an 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 to log general information on the SDK's internal processes.
// It extends the `WARNING` log level.
KameleoonLogger::setLogger(LogLevel::INFO);
// The `DEBUG` log level allows to log extra information on the SDK's internal processes.
// It extends the `INFO` log level.
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 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;
use Kameleoon\Exception\SiteCodeIsEmpty;
use Kameleoon\Exception\ConfigCredentialsInvalid;
$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
}
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
}
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 |
---|---|
ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either via the configuration file, or via parameters on the method). |
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;
use Kameleoon\Exception\SiteCodeIsEmpty;
use Kameleoon\Exception\ConfigCredentialsInvalid;
$siteCode = "a8st4f59bj";
try {
$cookieOptions = KameleoonClientConfig::createCookies(
"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)
);
$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
}
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). |
Feature flags and variations
isFeatureActive()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track
parameter)
This method was previously named 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.
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. |
$visitorCode = $kameleoonClient->getVisitorCode("example.com");
$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 accepte
}
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 generic Exception handler which will handle all exceptions.
echo "Exception: ", $e->getMessage(), "\n";
}
if ($hasNewCheckout)
{
// Implement new checkout code here
}
getVariation()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track
parameter)
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.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is required. |
featureKey | string | Key of the feature that you want to check the status of for the user. This field is required. |
track | bool | An optional parameter to enable or disable tracking of the feature evaluation (True by default). |
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. |
Return value
Type | Description |
---|---|
Variation | An assigned variation to a given visitor for a specific feature flag. |
Exceptions thrown
Type | Description |
---|---|
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 on your application). |
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. It is empty or longer than 255 characters. |
$featureKey = "new_checkout";
try {
$variation = $kameleoonClient->getVariation($visitorCode, $featureKey);
// disabling tracking
$variation = $kameleoonClient->getVariation($visitorCode, $featureKey, false);
}
catch (Kameleoon\Exception\FeatureNotFound $e) {
// The error has happened, the feature flag isn't found in 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 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;
}
getVariations()
- 📨 Sends Tracking Data to Kameleoon (depending on the
Track
parameter)
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
OnlyActive
is set totrue
, the methodgetVariations()
will return feature flags variations provided the user is not bucketed with theoff
variation. - The
Track
parameter 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.
Arguments
Name | Type | Description |
---|---|---|
visitorCode (required) | string | Unique identifier of the user. |
OnlyActive (optional) | boolean | An optional parameter indicating whether to return variations for active (true ) or all (false ) feature flags (Defaults to false ). |
Track (optional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation (Defaults to true ). |
Return value
Type | Description |
---|---|
map[string]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. |
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
}
getFeatureVariationKey()
- 📨 Sends Tracking Data to Kameleoon
This method is deprecated and will be removed in SDK version 5.0.0
. Use getVariation()
instead.
To get feature variation key, call the getFeatureVariationKey()
method of our SDK.
This method takes a visitorCode and featureKey as mandatory arguments to get variation key for a given user.
If such 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. 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.
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. |
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. |
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "featureKey";
$variationKey = "";
try {
$variationKey = $kameleoonClient->getFeatureVariationKey($visitorCode, $featureKey);
switch ($variationKey) {
case "on":
// Main variation key is selected for visitorCode
case "alternativeVariation":
// Alternative variation key
default:
// Default variation key
}
}
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 accepte
}
catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
// The feature flag is disabled for the environment
}
catch (Exception $e) {
// This is generic Exception handler which will handle all exceptions.
echo "Exception: ", $e->getMessage(), "\n";
}
getFeatureList()
Returns a list of feature flag keys currently available for the SDK
Arguments
Name | Type | Description |
---|---|---|
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. |
Return value
Type | Description |
---|---|
array | List of feature flag keys |
Exceptions thrown
Type | Description |
---|---|
DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
$arrayFeatureKeys = $kameleoonClient->getFeatureList();
getActiveFeatureListForVisitor()
This method is deprecated and will be removed in SDK version 5.0.0
. Use getActiveFeatures()
instead.
This method takes only input parameters: visitorCode. Result contains only active feature flags for a given visitor.
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 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. |
$visitorCode = "visitor";
$arrayFeatureFlagKeys = $kameleoonClient->getActiveFeatureListForVisitor($visitorCode);
getActiveFeatures()
This method is deprecated and will be removed in SDK version 5.0.0
. Use getVariations()
instead.
getActiveFeatures
method retrieves information about the active feature flags that are available for the specified visitor code.
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 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. |
$visitorCode = "visitor";
$arrayActiveFeatures = $kameleoonClient->getActiveFeatures($visitorCode);
Variables
getFeatureVariable()
- 📨 Sends Tracking Data to Kameleoon
- This method is deprecated and will be removed in SDK version
5.0.0
. UsegetVariation()
instead. - This method was previously named
obtainFeatureVariable
, which has been deprecated since SDK version3.0.0
and will be removed in a future releases.
To get variable of variation key associated with a user, call the getFeatureVariable()
method of our SDK.
This method takes a visitorCode, featureKey and variableName as mandatory arguments to get a variable of variation key for a given user.
If such a user has never been associated with this feature flag, the SDK returns a variable value of 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 variable value for previous associated variation. If the user does not match any of the rules, the variable of default value will be returned.
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 getFeatureVariable()
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.
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. |
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 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 the one in your code. |
DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "featureKey";
$variableName = "variableName"
try {
$variationValue = $kameleoonClient->getFeatureVariable($visitorCode, $featureKey, $variableName);
// Your custom code depending of 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 accepte
}
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 generic Exception handler which will handle all exceptions.
echo "Exception: ", $e->getMessage(), "\n";
}
getFeatureVariationVariables()
- This method is deprecated and will be removed in SDK version
5.0.0
. UsegetVariation()
instead. - This method was previously named
getFeatureAllVariables
, which was removed in SDK version4.0.0
.
To retrieve the all feature variables, call the getFeatureVariationVariables()
method of our SDK. 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. Throws an error (FeatureNotFound
) if the requested feature flag has not been found in the client configuration of the SDK. If variation key isn't found the method throws (FeatureVariationNotFound
) error.
Arguments
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 specified in your configuration. |
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). |
FeatureVariationNotFound | Exception indicating that the requested variation 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. |
DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
$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, ie 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 generic Exception handler which will handle all exceptions.
echo "Exception: ", $e->getMessage(), "\n";
}
Visitor data
getVisitorCode()
This method was previously named obtainVisitorCode
, which was removed in SDK version 4.0.0
.
This helper method should be called to obtain the Kameleoon visitorCode for the current visitor. This 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:
First we check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request can be found. If so, we will use this as the visitor identifier.
If no cookie / parameter is found in the current request, we either randomly generate a new identifier, or use the defaultVisitorCode argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table.
In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. Then this identifier value is finally returned by the method.
For more information, refer to this article.
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.
Arguments
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 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). |
require "vendor/autoload.php";
// The cookie's domain must be provided in the configuration file if no argument is given
$visitorCode = $kameleoonClient->getVisitorCode();
$visitorCode = $kameleoonClient->getVisitorCode($defaultVisitorCode); // default visitor code provided
addData()
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::$browsers["CHROME"]));
$kameleoonClient->addData(
$visitorCode,
new Kameleoon\Data\PageView("https://url.com", "title", array(3)),
new Kameleoon\Data\Conversion(32, 10, false)
);
The addData()
method adds targeting data 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 method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the flush. Noe that the trackConversion method also sends out any previously associated data, just like the flush method. The same is true for getFeatureFlagVariationKey and getFeatureFlagVariable methods if an experimentation rule is triggered.
Each visitor can only have one instance of associated data for most data types. However, CustomData
is an exception. Visitors can have one instance of associated CustomData
per customDataIndex
.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | String | Unique identifier of the user. This field is mandatory. |
dataTypes | Data | Custom data types which may be passed separated by a comma. |
flush()
- 📨 Sends Tracking Data to Kameleoon
flush()
takes the Kameleoon data associated with the visitor, then sends a tracking request along with all of the data that were added previously using the addData
method, that has not yet been sent when calling one of these methods. flush()
is non-blocking as the server call is made asynchronously.
flush()
allows you to control when the data associated with a given visitorCode
is sent to our servers. For instance, if you call addData()
a dozen times, it would be inefficient to send data to the server after each time addData()
is invoked, so all you have to do is call flush()
once at the end.
If you specify a visitorCode
, the flush()
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.
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 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. |
$visitorCode = $kameleoonClient->getVisitorCode();
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::$browsers["CHROME"]));
$kameleoonClient->addData(
$visitorCode,
new Kameleoon\Data\PageView("https://url.com", "title", array(3)),
new Kameleoon\Data\Conversion(32, 10, false)
);
$kameleoonClient->flush($visitorCode);
// if you operate with unique ID
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
$kameleoonClient->flush($visitorCode);
getRemoteData()
This method was previously named retrieveDataFromRemoteSource
, which was removed in SDK version 4.0.0
.
The getRemoteData()
method allows you to retrieve data (according to a key passed as argument) for specified siteCode (specified in KameleoonClientFactory.create()
) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.
Arguments
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 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. |
$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
}
getRemoteVisitorData()
getRemoteVisitorData()
is an asynchronous method for retrieving Kameleoon Visits Data for the visitorCode
from the Kameleoon Data API. The method adds the 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 for a better understanding of possible use cases.
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.
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.
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.
Arguments
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 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 filed 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. |
Here is the list of available Kameleoon\Types\RemoteVisitorDataFilter
options:
Name | Type | Description | Default |
---|---|---|---|
previousVisitAmount (optional) | int | Number of previous visits to retrieve data from. Number between 1 and 25 | 1 |
currentVisit (optional) | bool | If true, current visit data will be retrieved | true |
customData (optional) | bool | If true, custom data will be retrieved. | true |
pageViews (optional) | bool | If true, page data will be retrieved. | false |
geolocation (optional) | bool | If true, geolocation data will be retrieved. | false |
device (optional) | bool | If true, device data will be retrieved. | false |
browser (optional) | bool | If true, browser data will be retrieved. | false |
operatingSystem (optional) | bool | If true, operating system data will be retrieved. | false |
conversions (optional) | bool | If true, conversion data will be retrieved. | false |
experiments (optional) | bool | If true, experiment data will be retrieved. | false |
kcs (optional) | bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
$visitorCode = "visitorCode";
// Visitor data will be fetched and automatically added for `visitorCode`
$data_array = $kameleoonClient->getRemoteVisitorData($visitorCode, null); // default timeout will be used
$data_array = $kameleoonClient->getRemoteVisitorData($visitorCode, 1000); // 1000 milliseconds timeout
// If you only want to fetch data and add it yourself manually, set shouldAddData == `false`
$data_array = $kameleoonClient->getRemoteVisitorData(visitorCode, null, false); // default timeout will be used
$data_array = $kameleoonClient->getRemoteVisitorData(visitorCode, 1000, false); // 1000 milliseconds timeout
getVisitorWarehouseAudience()
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 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.
Arguments
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 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). |
$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);
setLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use personal data. Setting the legalConsent
parameter to false
limits the types of data that you can include in tracking requests. This 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.
Arguments
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). |
$visitorCode = $kameleoonClient->getVisitorCode();
$kameleoonClient->setLegalConsent($visitorCode, true);
Goals and third party analytics
getEngineTrackingCode()
Kameleoon offers built-in integrations with various analytics and CDP solutions, such as Mixpanel, Google Analytics 4, Segment.... To ensure that you can track and analyze your server-side experiments, Kameleoon provides a method GetEngineTrackingCode()
that returns the JavasScript code to be inserted in your page to send automatically the exposure events to the analytics solution you are using.The SDK builds a tracking code for your active analytics solution based on the experiments that the visitor has triggered in the last 5 seconds.
For more information about hybrid experimentation, please refer to this documentation.
To benefit from this feature, you will need to implement both the PHP SDK and our Kameleoon JavaScript tag. We recommend you implement the [Kameleoon Asynchronous tag], which you can install before your closing <body>
tag in your HTML page, as it will be only used for tracking purposes.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | The user's unique identifier. This field is mandatory. |
Return value
Type | Description |
---|---|
string | JavaScript code to be inserted in your page |
engineTrackingCode := $kameleoonClient->getEngineTrackingCode($visitorCode)
// Example JavaScript code that can be returned:
//
// window.kameleoonQueue = window.kameleoonQueue || [];
// window.kameleoonQueue.push(['Experiments.assignVariation', experiment1ID, variation1ID]);
// window.kameleoonQueue.push(['Experiments.trigger', experiment1ID, true]);
// window.kameleoonQueue.push(['Experiments.assignVariation', experiment2ID, variation2ID]);
// window.kameleoonQueue.push(['Experiments.trigger', experiment2ID, true]);
//
// Here, experiment1ID, experiment2ID and variation1ID, variation2ID represent
// the specific experiments and variations that the specified user has been assigned to
trackConversion()
- 📨 Sends Tracking Data to Kameleoon
To track conversion, use the trackConversion()
method. This method requires visitorCode and goalID to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitorCode usually is 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.
If you specify a visitorCode
, the trackConversion()
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.
Arguments
Name | Type | Description |
---|---|---|
visitorCode | string | Unique identifier of the user. This field is mandatory. |
goalID | int | ID of the goal. This field is mandatory. |
revenue | float | Revenue of the conversion. 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. |
require "vendor/autoload.php";
$kameleoonClient = Kameleoon\KameleoonClientFactory::create("a8st4f59bj", false, "/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);
Data types
You can use the following pre-defined data types from Kameleoon\Data
.
Browser
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::$browsers["CHROME"]));
Name | Type | Description |
---|---|---|
browser | Associative Array | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory. |
PageView
$kameleoonClient->addData(
$visitorCode,
new Kameleoon\Data\PageView("https://url.com", "title", array(3))
);
Name | Type | Description |
---|---|---|
url | String | URL of the page viewed. This field is mandatory. |
title | String | Title of the page viewed. This field is mandatory. |
referrers | array | Referrers of viewed pages. This field is optional. |
The index (ID) of the referrer is available on our Back-Office, in the Acquisition channel configuration page. Be careful: this index starts at 0, so the first acquisition channelyou create for a given site would have the ID 0, not 1.
Conversion
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Conversion(32, 10, false));
Name | Type | Description |
---|---|---|
goalID | Integer | ID of the goal. This field is mandatory. |
revenue | Float | Conversion revenue. This field is optional. |
negative | Boolean | Defines if the revenue is positive or negative. This field is optional. |
CustomData
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "some custom value"));
Name | Type | Description |
---|---|---|
index | Integer | Index / ID of the custom data to be stored. This field is mandatory. |
value | String | Value of the custom data to be stored. This field is mandatory. |
The index (ID) of the custom data is available on our Back-Office, in the Custom data configuration page. Be careful: this index starts at 0, so the first custom data you create for a given site would have the ID 0, not 1.
Device
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Device(Kameleoon\Data\Device::PHONE));
Name | Type | Description |
---|---|---|
type | int | List of devices: PHONE, TABLET, DESKTOP. This field is mandatory. |
UserAgent
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UserAgent("TestUserAgent"));
Name | Type | Description |
---|---|---|
value | string | The User-Agent value that will be sent with tracking requests. This field is mandatory. |
Store information on the user-agent of the visitor. Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. Kameleoon also uses the UserAgent
field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. For more details, see the help article on bot filtering.
If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.
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. When you add UniqueIdentifier
for a visitor, the SDK links the flushed data with the visitor associated with the specified identifier.
The UniqueIdentifier
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.
Name | Type | Description |
---|---|---|
value | bool | Parameter for specifying if the visitorCode is a unique identifier. This field is required. |
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
OperatingSystem
OperatingSystem
contains information about the operating system on the visitor's device.
Each visitor can only have one OperatingSystem
. Adding a second OperatingSystem
overwrites the first one.
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\OperatingSystem(Kameleoon\Data\OperatingSystem::WINDOWS));
Name | Type | Description |
---|---|---|
type | int | List of operating systems: WINDOWS , MAC , IOS , LINUX , ANDROID and WINDOWS_PHONE . This field is required. |
Cookie
Cookie
contains information about the cookie stored on the visitor's device.
Each visitor can only have one Cookie
. Adding second Cookie
overwrites the first one.
$cookie = new Kameleoon\Data\Cookie([
"k1" => "v1",
"k2" => "v2",
]);
$kameleoonClient->addData($visitorCode, $cookie);
Name | Type | Description |
---|---|---|
cookies | array | A string object map consisting of cookie keys and values. This field is required. |
Geolocation
Geolocation
contains the visitor's geolocation details.
Each visitor can only have one Geolocation
. Adding a second Geolocation
overwrites the first one.
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Geolocation("France", "Île-de-France", "Paris"));
Name | Type | Description |
---|---|---|
country | string | The country of the visitor. The field is required. |
region | string | The region of the visitor. The field is optional. |
city | string | The city of the visitor. The field is optional. |
postalCode | string | The postal code of the visitor. The field is optional. |
latitude | float | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. The field is optional. |
longitude | float | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. The field is optional. |
Returned Types
Variation
Variation
contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
Name | Type | Description |
---|---|---|
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. |
- The
Variation
object provides details about the assigned variation and its associated experiment, while theVariable
object contains specific details about each variable within a variation. - Ensure that your code handles the case where
id
orexperimentId
may benull
, indicating a default variation. - The
variables
array might be empty if no variables are associated with the variation.
Example code
// 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. |
Example code
// 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;