← Back to serbanghita/Mobile-Detect

How to Deploy & Use serbanghita/Mobile-Detect

Mobile Detect Deployment and Usage Guide

This guide provides comprehensive instructions for deploying and using Mobile Detect, a lightweight PHP class for detecting mobile devices.

1. Prerequisites

To use Mobile Detect, you need the following:

  • PHP: Version 8.0 or higher is recommended for the latest 4.8.x branch.
  • Composer: A dependency manager for PHP.

2. Installation

Install Mobile Detect using Composer.

  1. Create a new PHP project (if you don't have one):

    mkdir my-mobile-app
    cd my-mobile-app
    composer init
    
  2. Install Mobile Detect via Composer:

    composer require mobiledetect/mobiledetectlib
    

    This command will install the latest recommended version (4.8.x) of Mobile Detect and its dependencies.

3. Configuration

Mobile Detect generally requires no explicit configuration files or environment variables. Detection logic is based on HTTP headers and User-Agent strings, which are automatically accessed from the PHP $_SERVER superglobal.

Optional: Caching

Mobile Detect includes an in-memory cache implementation (Detection\Cache\Cache) that adheres to PSR-16. While not strictly a configuration, you can integrate a PSR-16 compatible cache for performance if needed.

Example of using the built-in cache (advanced usage):

<?php

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

use Detection\MobileDetect;
use Detection\Cache\Cache;

$cache = new Cache();
$detect = new MobileDetect(null, null, $cache);

// The cache will be used for subsequent detection calls
$isMobile = $detect->isMobile();

4. Build & Run

Mobile Detect is a PHP library, so there's no "build" step in the traditional sense. You integrate it directly into your PHP application.

Running Locally (Development)

  1. Create a PHP file (e.g., index.php) in your project root.

  2. Add the following code to index.php to demonstrate basic usage:

    <?php
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    use Detection\MobileDetect;
    
    $detect = new MobileDetect();
    
    echo "<h1>Mobile Detect Demo</h1>";
    echo "<p>Is a mobile device? " . ($detect->isMobile() ? 'Yes' : 'No') . "</p>";
    echo "<p>Is a tablet device? " . ($detect->isTablet() ? 'Yes' : 'No') . "</p>";
    echo "<p>Detected OS: " . $detect->getOperatingSystem() . "</p>";
    echo "<p>Detected Browser: " . $detect->getBrowser() . "</p>";
    echo "<p>User Agent: " . $detect->getUserAgent() . "</p>";
    
    // Example of specific detection
    if ($detect->is('iOS')) {
        echo "<p>This is an iOS device.</p>";
    }
    if ($detect->is('AndroidOS')) {
        echo "<p>This is an Android device.</p>";
    }
    if ($detect->is('iPad')) {
        echo "<p>This is an iPad.</p>";
    }
    ?>
    
  3. Run a local PHP development server:

    php -S localhost:8000
    
  4. Open your web browser and navigate to http://localhost:8000. You will see the detection results based on the User-Agent of the browser you are using.

Running the Example Script

The project includes an example script scripts/example.php that demonstrates basic usage:

php scripts/example.php

This script will output bool(true) or bool(false) for isMobile() and isTablet() based on the hardcoded User-Agent string.

Running Tests

To run the project's test suite:

vendor/bin/phpunit -v -c tests/phpunit.xml --coverage-html .coverage

This command executes the PHPUnit tests and generates a code coverage report in the .coverage directory.

Exporting to JSON

Mobile Detect provides a script to export its detection rules (headers, UA patterns) to a JSON file. This is useful for integrating the detection logic into other languages or systems.

php scripts/export_to_json.php

This will create a MobileDetect.json file in the project root.

5. Deployment

Mobile Detect is a PHP library and is deployed as part of a larger PHP application.

  1. Ensure Composer Dependencies are Installed: On your production server, navigate to your application's root directory and run:

    composer install --no-dev --optimize-autoloader
    

    This installs only production dependencies and optimizes the autoloader for faster performance.

  2. Integrate into your PHP application: Include the Composer autoloader (vendor/autoload.php) in your main application entry point.

    require_once __DIR__ . '/vendor/autoload.php';
    
    use Detection\MobileDetect;
    
    $detect = new MobileDetect();
    // ... use $detect object in your application logic
    
  3. Deployment Platforms:

    • Shared Hosting / VPS: Upload your entire project directory (including vendor/ and composer.json/composer.lock) to your web server. Ensure your web server (Apache, Nginx) is configured to serve PHP files.
    • Cloud Platforms (AWS EC2, Google Cloud Compute Engine, Azure VMs): Deploy your application as you would any other PHP application on these virtual machines.
    • PaaS (Platform as a Service) like Heroku, AWS Elastic Beanstalk, Google App Engine, Azure App Service: These platforms typically detect PHP projects automatically. Ensure your composer.json is correctly configured, and the platform will handle composer install during deployment.
    • Docker: Create a Dockerfile for your PHP application. Include the composer install step in your Docker build process.
    # Example Dockerfile snippet
    FROM php:8.2-apache
    
    WORKDIR /var/www/html
    
    COPY . .
    
    RUN composer install --no-dev --optimize-autoloader
    
    # ... rest of your Dockerfile
    

6. Troubleshooting

  • Class 'Detection\MobileDetect' not found:

    • Cause: The Composer autoloader is not included or composer install was not run.
    • Solution: Ensure require_once __DIR__ . '/vendor/autoload.php'; is at the top of your PHP script, and run composer install in your project directory.
  • Incorrect Device Detection:

    • Cause 1: Outdated Mobile Detect library. Device User-Agents change frequently.
    • Solution 1: Update the library: composer update mobiledetect/mobiledetectlib.
    • Cause 2: Custom User-Agent string being passed that doesn't accurately represent the device.
    • Solution 2: Ensure you are not overriding the User-Agent if you intend to detect the current client. If you are, ensure the provided User-Agent is valid.
    • Cause 3: Proxy servers or CDN services (like CloudFront) might strip or modify HTTP headers. Mobile Detect can use specific CloudFront headers.
    • Solution 3: If using CloudFront, Mobile Detect automatically checks CloudFront-Is-Mobile-Viewer, CloudFront-Is-Tablet-Viewer, etc. Ensure these headers are being passed correctly by your CDN configuration.
  • Performance Issues:

    • Cause: Repeated calls to isMobile() or isTablet() within a single request, especially on high-traffic sites, can be slightly inefficient without caching.
    • Solution: Implement a PSR-16 compatible cache (e.g., the built-in Detection\Cache\Cache or a more robust solution like Redis/Memcached with a PSR-16 adapter) and pass it to the MobileDetect constructor.
  • CacheInvalidArgumentException:

    • Cause: An invalid key was used when interacting with the cache (e.g., an empty string or a string containing reserved characters).
    • Solution: Ensure cache keys are valid strings according to PSR-16 specifications.
  • MobileDetectException:

    • Cause: A generic error within the Mobile Detect library. Check the exception message for details.
    • Solution: Review the specific exception message and stack trace. This might indicate an internal issue or an unexpected input. Report bugs to the project's issue tracker if it seems to be a library fault.