WURFL OnSite PHP API: User Guide
================================
> **Note:** If you are moving from our legacy Database API to PHP API, please refer to our detailed [migration guide](https://docs.scientiamobile.com/guides/upgrade-to-wurfl-onsite-php-api-from-onsite-database-api "Moving to PHP API from DBAPI") to ensure a smooth transition. Also, there are breaking changes in API release v1.8. For documentation of releases before API v1.8 please refer to the README file included with that version. If you need aditional help for versions prior to 1.8 feel free to contact us at: <support@scientiamobile.com>.*


Installation
------------

#### Start a Trial or Purchase a License
To access the installation package, please create a [free ScientiaMobile account](https://my.scientiamobile.com/register) and [contact us](https://scientiamobile.com/start-trial-2/) to initiate a trial or to purchase a license.

#### Where to Download the Installation Package
To download the installation package, [log in to your existing ScientiaMobile account](https://my.scientiamobile.com/). On the [My Account](https://my.scientiamobile.com/account) page of the Customer Vault, click **Manage** on your OnSite license, then click **Downloads**. Click **Download** next to a release of the WURFL API associated with your license to download it directly. To download it from the command line or another machine instead, open the **⋯** menu next to the release and choose **Copy download link**, **Copy curl command**, or **Show link and command...**

> **Note:** Download links are short-lived and only download the selected package. Copy a new link each time you need one, rather than saving it in scripts.

For details on downloading WURFL data snapshots, please refer to [this documentation](https://docs.scientiamobile.com/guides/wurfl-snapshot-generator).<br>

Once you have downloaded the latest release, extract the files to be accessible from your PHP enabled webserver.

> **Note:** The WURFL API is closely tied to the `wurfl.xml` file. New versions
of the `wurfl.xml` are compatible with old versions of the API by nature,
but the reverse is **not** true. Old versions of the `wurfl.xml` are **not**
guaranteed to be compatible with new versions of the API.

Requirements
------------

- PHP >= 7.4
- extension: xml (XMLReader)
- [Composer](https://getcomposer.org/) - The WURFL OnSite PHP API uses Composer which is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. Download and instructions can be found [here](https://getcomposer.org/download/).


Install dependencies
--------------------
Inside of your project folder, run the following command:

```shell
composer install --optimize-autoloader --no-dev
```

WURFL Data Snapshot
-----
To perform lookups, you will need a copy of your WURFL data snapshot (also referred to as the `wurfl.xml`). While there is one included in the release package, it is intended to be a sample and will not contain all of your licensed capabilities. Your licensed WURFL data snapshot can be accessed by [following these directions](https://docs.scientiamobile.com/guides/wurfl-snapshot-generator).
Adds WURFL PHP API to an existing project using composer.json
-------------------------------------------------------------

If your project uses Composer, you can simplify maintenance by specifying
the WURFL PHP API as an [artifact](https://getcomposer.org/doc/05-repositories.md#artifact)
repository:

- Copy the WURFL PHP API ZIP package in a folder which will contain the archives
- Add the following configuration to your composer.json:

```json
"repositories": [
  {
      "type": "artifact",
      "url": "/path/to/directory/with/zips/"
  }
],
"require": {
  "scientiamobile/wurfl-api": "*"
}
```

- Run `composer install` to install the dependencies

> **Note:** To update the package, simply copy the new ZIP archive in the package
folder and run `composer update`

Configuring WURFL
-----------------

Starting in version 1.8.0.0, the API uses a dependency container to configure and inject the required dependencies.

To configure WURFL you need to create a PHP configuration file returning a Container object.

As reference or starting point, please refer to the `config/config.php.example` file.

1. Create a new WURFL Dependency Container with optional settings

   ```php
   // Example: Create WURFL Dependency Container
   $container = new \ScientiaMobile\WURFL\Container\Container([
       'wurfl_snapshot_url' => 'https://data.scientiamobile.com/xxxxx/wurfl.zip',
       'wurfl_capability_filter' => [
           'device_os',
           'device_os_version',
           // ...
       ],
       'wurfl_patches' => [
           '/full/path/to/patch-1.xml',
           '/full/path/to/patch-2.xml',
           // ...
       ],
       // ...
   ]);
   ```

   The Container takes an optional argurment as an associative array of settings with the following keys:

     - **wurfl_db**: a full path to the WURFL DB file (default to: `resources/wurfl.xml`)
     - **wurfl_snapshot_url**: The [WURFL Snapshot](https://www.scientiamobile.com/update-api-xml-device-detection#xml) URL from your [Customer Vault](https://my.scientiamobile.com/account) (click **Manage** next to your OnSite license, then **Snapshot generator**). Ex. https://data.scientiamobile.com/xxxxx/wurfl.zip.
     - **wurfl_patches**: an array containing the WURFL patches' full path
     - **wurfl_capability_filter**: an array with the capabilities to load in order to reduce memory usage and increase performance
     - **wurfl_storage_path**: the absolute path to the storage dir. Default to "storage"
     - **wurfl_debug**: a boolean that enables the debug mode (default to: `false`)

   > **Note:** if `wurfl_snapshot_url` is specified the `wurfl_db` setting will be ignored.

2. Create a Storage adapter using either the StorageFactory, or by simply instantiating one of the Storage classes.

   The API supports the following storage mechanisms:
   - File (default)
   - SQLite through the PDO extension
   - Redis through the redis extension
   - MySQL through the PDO or the mysqli extension
   - MongoDB through the mongodb extension
   - Memory

   ```php
   // Example: Create a File storage adapter
   use ScientiaMobile\WURFL\Storage\StorageFactory;
   $storage = StorageFactory::createFileStorage('/path/to/storage/folder');
   ```
### <a name="cache"></a>
3. Create a Cache adapter using either the CacheFactory factory, or by simply instantiating one of the Cache classes.
   The API supports the following caching mechanisms:
   - File (default)
   - APCu (APC User Cache)
   - Redis
   - SQLite
   - Memcache
   - MySQL
   - Null (no caching)

   ```php
   // Example: Create a File cache adapter
   use ScientiaMobile\WURFL\Cache\CacheFactory;
   use ScientiaMobile\WURFL\Cache\CacheAdapterInterface;

   // Time to live for cache item
   $ttl = CacheAdapterInterface::NEVER; //Default
   $cache = CacheFactory::createFileCache($ttl, '/path/to/storage/folder');
   ```

4. Add the storage and cache adapters to the container

   ```php
   $container->setStorageAdapter($storage);
   $container->setCacheAdapter($cache);
   ```

> **Note:** Since the default configuration uses the File adapter for both Storage and Caching,
 you'll need to make sure your webserver can write to the **storage** directories.

> **Note:** As reference on how configure and use the Evalution version please refer to the section: [WURFL PHP API Basic Usage for the Evaluation version](#wurfl_eval_usage)

### <a name="updater"></a>
WURFL Updater
-------------

API version 1.8.0.0 introduces WURFL updater - a new command line utility which allows a client using WURFL to automatically update while the standard WURFLEngine is running and serving requests.
In order to use the WURFL Updater, you must have your personal WURFL Snapshot URL (`wurfl_snapshot_url`) in the following format: https://data.scientiamobile.com/xxxxx/wurfl.zip where xxxxx is replaced with you personal access token.
Also, do note that the `wurfl_storage_path` specified in the dependency container must be writable from the process/task and a wurfl.zip file must already be present in order for the Updater to run and determine whether or not the file needs to be updated.

The `wurfl-updater` utility is located under:

- `/your/project/root/path/vendor/bin/` for project that uses the API as composer dependency
- `/path/to/wurfl-api/` for project that uses the API as standalone library

The `wurfl-updater` utility can be used to run `on demand` or `periodic` updates.

### Running "periodic" updates.

This is the suggested configuration since it allows periodic checks for an updated version of the wurfl.zip file, downloads it, and builds the repository with the updated version.

The quickest way to enable periodic updates is to use a time-based job scheduler, like a crontab:

```shell
# Crontab example
# .--------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | |   .--------- day of month (1 - 31)
# | |   | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | |   | | .----- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat
# | |   | | |
# * *   * * *	<user>	<command>

# Run the wurfl-updater script with daily frequency
30 3 * * *       www-data  /path/to/php -d memory_limit=1024M /path/to/wurfl-updater -c /path/to/config.php > /dev/null
```

### Running "on demand" update.

```
php -d memory_limit=1024M /path/to/wurfl-updater -c /path/to/config.php
```

On demand update runs only once per call.


WURFL PHP API Basic Usage
-------------------------

```php
require_once './vendor/autoload.php';

// Require the dependency container object
$container = require_once '/path/to/config/config.php';
// Create a new instance of WURFLEngine
$wurfl_engine = new \ScientiaMobile\WURFL\WURFLEngine($container);
// Get the device for the current request
$device = $wurfl_engine->getDeviceForHttpRequest();
// Get the value for a static capability
$device->getCapability("is_wireless_device");
// Get the value for a virtual capability
$device->getVirtualCapability("is_smartphone");
```

>**IMPORTANT:**  Empty header values are treated as valid and those headers are not discarded. If you build your HTTP request programmatically from a data source such as logs, DB data, spreadsheet, etc., please make sure that you DO NOT add headers with empty strings as values (this may also be the result of "casting" a  `NULL`  /  `NONE`  /  `NaN`  to a string):
><br></br>
> *Avoid:*
> ```
> {headerName}:{headerValue}
> ```
>*Use:*
>```
>if  notNullOrEmpty(headerValue):
>     {headerName}:{headerValue}
>```

<a name='wurfl_eval_usage'></a> WURFL PHP API Basic Usage for the Evaluation version
----------------------------------------------------

The Evaluation package comes with an XML file containing several of our popular WURFL Device Capabilities
that can be loaded directly from the API without use of the WURFL Updater.

```php
require_once './vendor/autoload.php';

// Require the dependency container object
$container = new \ScientiaMobile\WURFL\Container();
// Build the WURFL Repository using the WURFL evaluation XML
\ScientiaMobile\WURFL\Repositories\RepositoryManager::build($container);
// Create a new instance of WURFLEngine
$wurfl_engine = new \ScientiaMobile\WURFL\WURFLEngine($container);
// Get the device for the current request
$device = $wurfl_engine->getDeviceForHttpRequest();
// Get the value for a static capability
$device->getCapability("is_wireless_device");
// Get the value for a virtual capability
$device->getVirtualCapability("is_smartphone");
```

> **Note:** Because this configuration of the WURFL repository is built directly from the WURFL API, the first request could take a few seconds to be served.

Capability Filtering
--------------------
### <a name="capabilityfilter"></a>
To reduce memory usage and increase performance, specify a subset of the 500+ WURFL capabilities. You can set the desired capabilities
as settings in the Dependency Container:

```php
// Example: Create WURFL Dependency Container
$container = new \ScientiaMobile\WURFL\Container\Container([
    'wurfl_capability_filter' => [
        'device_os',
        'device_os_version',
        ...
    ]
]);
```

If you make any changes, or add a capability filter, you will need to
reload the WURFL file so that only the capabilities you've specified will
be loaded. Do note that the auto-reload system will not detect the change
in your configuration and will reload the WURFL data automatically. You
will need to either touch the WURFL file, or delete your persistence folder.

>**Note**: If you are upgrading from a previous version, do note that, starting in WURFL API version 1.8.0.0,
you no longer need to specify WURFL mandatory capabilities.

Virtual Capabilities
--------------------

Virtual capabilities are an important feature of the WURFL API that
obtain values related to the requesting agent out of the HTTP request
as a whole (as opposed to limiting itself to capabilities that are found
in WURFL).

In order to compute its final returned value, a virtual capability may
look at regular (non-virtual) capabilities as well as parameters
derived from the HTTP request at run-time. Virtual capabilities
are useful to model aspects of the HTTP Client that are not easily captured
through the finite number of profiles in WURFL.

To retrieve the value of a virtual capability, use the `getVirtualCapability()`
method from a `Device` object:

```php
$is_smartphone = $device->getVirtualCapability('is_smartphone');
```

<table class="table table-bordered table-striped table-hover">
  <thead>
    <tr style="background-color:#111;color:#E5E5E5;">
      <th>Variable Name</th>
      <th>Type</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>advertised_app_name</strong></td>
      <td>string</td>
      <td>Returns the name of the application that generated the User-Agent or the HTTP request.</td>
    </tr>
    <tr>
      <td><strong>advertised_architecture</strong></td>
      <td>enumerable</td>
      <td>This virtual capability returns the architecture of the device based on analysis of the Sec-Ch-Ua-Arch high entropy User-Agent Client Hint.</td>
    </tr>
    <tr>
      <td><strong>advertised_browser</strong></td>
      <td>string</td>
      <td>Infers the name of the browser based on user-agent string analysis (and possibly the analysis of other HTTP headers and WURFL capabilities).</td>
    </tr>
    <tr>
      <td><strong>advertised_browser_version</strong></td>
      <td>string</td>
      <td>Infers the version of the browser based on user-agent string analysis (and possibly the analysis of other HTTP headers and WURFL capabilities).</td>
    </tr>
    <tr>
      <td><strong>advertised_device_os</strong></td>
      <td>string</td>
      <td>Infers the name of the Device OS based on user-agent string analysis (and possibly the analysis of other HTTP headers and WURFL capabilities).</td>
    </tr>
    <tr>
      <td><strong>advertised_device_os_version</strong></td>
      <td>string</td>
      <td>Infers the name of the Device OS Version based on user-agent string analysis (and possibly the analysis of other HTTP headers and WURFL capabilities).</td>
    </tr>
    <tr>
      <td><strong>complete_device_name</strong></td>
      <td>string</td>
      <td>Concatenates brand name, model name and marketing name (where available) of a device into a single string.</td>
    </tr>
    <tr>
      <td><strong>device_name</strong></td>
      <td>string</td>
      <td>Concatenates brand name and marketing name of a device into a single string. If marketing name is not available, model name is used instead.</td>
    </tr>
    <tr>
      <td><strong>form_factor</strong></td>
      <td>string</td>
      <td>Returns the device's form factor based on categorization provided by multiple capability tests</td>
    </tr>
    <tr>
      <td><strong>generalized_browser_type</strong></td>
      <td>enumerable</td>
      <td>Returns a high-level categorization of the browser type, useful for distinguishing human traffic from automated requests. An empty string is returned as a default/fallback value.</td>
    </tr>
    <tr>
      <td><strong>generalized_os_brand</strong></td>
      <td>enumerable</td>
      <td>Identifies the company that owns or maintains the device's operating system (e.g., Apple for iOS, Google for Android). An empty string is returned as a default/fallback value.</td>
    </tr>
    <tr>
      <td><strong>is_android</strong></td>
      <td>boolean</td>
      <td>Checks if device runs any version of Android OS. This virtual capability relies on the device_os capability.</td>
    </tr>
    <tr>
      <td><strong>is_app</strong></td>
      <td>boolean</td>
      <td>True if the Requesting HTTP Client is an App or not. Please note that browsers are not considered apps for is_app capability purposes and will not return true .</td>
    </tr>
    <tr>
      <td><strong>is_app_webview</strong></td>
      <td>boolean</td>
      <td>True if a HTTP request is from an app based webview. Please note that browsers are not considered apps for is_app_webview capability purposes and will not return true .</td>
    </tr>
    <tr>
      <td><strong>is_full_desktop</strong></td>
      <td>boolean</td>
      <td>This is just an ALIAS for  ux_full_desktop.</td>
    </tr>
    <tr>
      <td><strong>is_generic</strong></td>
      <td>boolean</td>
      <td>This virtual capability will return <code>true</code> if the WURFL ID contains <code>generic</code> and <code>false</code> in all other cases.</td>
    </tr>
    <tr>
      <td><strong>is_html_preferred</strong></td>
      <td>boolean</td>
      <td>True if the device is better served with HTML. Capability relies on  preferred_markup  (markup group).</td>
    </tr>
    <tr>
      <td><strong>is_ios</strong></td>
      <td>boolean</td>
      <td>True if device runs any version of iOS. This virtual capability relies on the device_os (product_info group) capability.</td>
    </tr>
    <tr>
      <td><strong>is_largescreen</strong></td>
      <td>boolean</td>
      <td>True if the device has a horizontal screen resolution greater than 320 pixels. Relies on the  resolution_width  ( display  group) capability.</td>
    </tr>
    <tr>
      <td><strong>is_mobile</strong></td>
      <td>boolean</td>
      <td>This is an ALIAS for is_wireless_device. True if a device is wireless (WiFi, 3G, LTE etc.). Specifically a mobile phone or a tablet are considered as wireless devices, but a desktop PC or a laptop are not.</td>
    </tr>
    <tr>
      <td><strong>is_phone</strong></td>
      <td>boolean</td>
      <td>True if a device is a mobile phone.</td>
    </tr>
    <tr>
      <td><strong>is_robot</strong></td>
      <td>boolean</td>
      <td>True if the HTTP Client is a Bot (robot, crawler or other programmable agent that stalks the web).</td>
    </tr>
    <tr>
      <td><strong>is_smartphone</strong></td>
      <td>boolean</td>
      <td>True if device conforms to ScientiaMobile's definition of a Smartphone.</td>
    </tr>
    <tr>
      <td><strong>is_touchscreen</strong></td>
      <td>boolean</td>
      <td>True if the device has a touch screen. Mostly an alias for  pointing_method  ==  touchscreen  ( product_info group) capability.</td>
    </tr>
    <tr>
      <td><strong>is_windows_phone</strong></td>
      <td>boolean</td>
      <td>True if device runs any version of Windows Phone OS. This virtual capability relies on the device_os (product_info group) capability.</td>
    </tr>
    <tr>
      <td><strong>is_wml_preferred</strong></td>
      <td>boolean</td>
      <td>True if the device is better served with WML. Capability relies on  preferred_markup  ( markup  group).</td>
    </tr>
    <tr>
      <td><strong>is_xhtmlmp_preferred</strong></td>
      <td>boolean</td>
      <td>True if the device is better served with XHTML MP (Mobile Profile). Capability relies on  preferred_markup  (markup group).</td>
    </tr>
    <tr>
      <td><strong>pixel_density</strong></td>
      <td>numeric</td>
      <td>The number of physical pixels per inch in a screen or display. Also referred to as Pixels per Inch (PPI).</td>
    </tr>
    <tr>
      <td><strong>robot_family</strong></td>
      <td>enumerable</td>
      <td><p>If a device's user-agent is identified as a robot, then the robot_family capability will return a categorization based on the nature and intention of the robot.</p>


<p></p></td>
    </tr>
  </tbody>
</table>

Populating IAB's OpenRTB V2 (ORTB2) Device Type
---------------------------------
### <a name="ortb"></a>
Starting with WURFL API 1.13.6.0, `getORTB2DeviceType()` will return a value corresponding to the device's OpenRTB V2 devicetype. More information on this topic is available in [this blog post](https://scientiamobile.com/update-how-to-populate-iabs-openrtb-device-object/).
> **Note:** The following static capabilities: is_ott, is_console, physical_form_factor and the following virtual capabilities: form_factor are required to be present in the loaded wurfl.xml file for this method.

Checking User-Agent frozenness and HTTP headers quality
---------------------------------
### <a name="headerquality"></a>
Starting from version 1.12.5.0 the `HttpRequest` class provides two new methods: `isUaFrozen()`, `headerQuality()`.

`isUaFrozen(string $user_agent)` returns a boolean value which, if true, means that the input User-Agent string won't be updated by the sender browser.

`headerQuality()` returns an enumeration value that describes the HTTP headers quality. It has three possible values:

  - **HEADER_QUALITY_FULL**: all the headers needed for a successful WURFL detection are present. Eg. a header with all UA-CH header fields present
  - **HEADER_QUALITY_BASIC**: only some of the headers needed for a successful WURFL detection are present.
  - **HEADER_QUALITY_NONE**: no UA-CH headers are present


Example:

```php
$headers = [
  'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.0.0 Safari/537.36',
  'Sec-Ch-Ua' => '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
  'Sec-Ch-Ua-Platform' => 'Linux',
];
$request = new HttpRequest($headers);
$is_ua_frozen = $request->isUaFrozen(); // true
$header_quality = $request->headerQuality(); // basic
```

Enable Fast Desktop Browser Match
---------------------------------

> Deprecated since 1.9.5.0

Use this option when you have significant amounts of desktop browser traffic compared to mobile device.
Will return "generic_web_browser" wurfl_id for the majority of web browsers.

```php
// Enable the fast desktop browser match.
$wurfl_engine->enableFastDesktopBrowserMatch();
```

Examples
--------

There is a usage example included with the PHP API in the examples/demo folder.

The file `examples/demo/index.php` demonstrates how you can use the API to
display the capabilities of a visiting device.


> **IMPORTANT - Decommissioning of Engine Target options**
> -----------
> Prior to version 1.9 of the API, users could choose between High Accuracy and High Performance engine optimization options.
> These options had been introduced years ago to manage the behavior of certain web browsers and their tendency to present
> "always different" User-Agent strings that would baffle strategies to cache similar WURFL queries in memory.
> As the problem has been solved by browser vendors, the need to adopt this strategy has diminished and ultimately
> disappeared (i.e. there was no longer much to be gained with the high-performance mode in most circumstances) and
> ScientiaMobile elected to deprecate this option to simplify configuration and go in the direction of uniform API
> behavior in different contexts.
> Customers who may find themselves in the unlikely situation of having to analyze significant amounts of legacy web traffic
> may still enable the old high-performance internal behavior by enabling the ENGINE_TARGET_FAST_DESKTOP_BROWSER_MATCH
> option in their engine target configuration.
> Please note that users with the old HIGH_PERFORMANCE or HIGH_ACCURACY target engine will not receive any error.
> The old behavior will not be triggered, though. The DEFAULT target (corresponding to the old HIGH_ACCURACY) will be used instead.


-------

**&copy; 2026 ScientiaMobile Inc.<br>
All Rights Reserved.**

**NOTICE:** All information contained herein is, and remains the property of ScientiaMobile Incorporated
and its suppliers, if any.  The intellectual and technical concepts contained herein are proprietary to
ScientiaMobile Incorporated and its suppliers and may be covered by U.S. and Foreign Patents, patents
in process, and are protected by trade secret or copyright law. Dissemination of this information or
reproduction of this material is strictly forbidden unless prior written permission is obtained from
ScientiaMobile Incorporated.
